jquery
  1. jquery-first

JQuery first()

The first() method in JQuery allows you to select the first element in a set of matched elements.

Syntax

The syntax for first() is as follows:

$(selector).first();
  • selector: the element(s) to be selected

Use

The first() method is often used when you want to select only the first element of a group of elements. For example, if you have a list of items and you want to highlight only the first item, you can use the first() method to select it.

Example

Here is an example of using first() method in JQuery:

<!DOCTYPE html>
<html>
<head>
    <title>JQuery first() Method Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li").first().css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <h2>JQuery first() Method Example</h2>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
</body>
</html>
Try Playground

In this example, we use the first() method to select the first <li> element in an unordered list and change its background color to yellow.

Summary

The first() method in JQuery allows you to easily select the first element in a set of matched elements. It is commonly used when you want to perform an action on only the first element of a group of elements. By specifying first(), you can quickly and easily target the first element of a set.

Published on: