• jQuery Video Tutorials

jQuery :first Selector



The :first selector is a jQuery selector that selects the first element in a set of matched elements.

When applied to a set of matched elements, the :first selector returns the first element found within that set. If no elements match the selector expression, an empty jQuery object is returned.

Note: If we want to select the last element in a set of matched elements, we need to use the :last selector.

Syntax

Following is the syntax of :first selector in jQuery −

$("selector:first")

Parameters

Following is the explantion of above syntax −

  • selector: This is a CSS selector. It specifies the criteria for selecting elements. For example:
  • "div" selects all <div> elements.

  • ".class" selects all elements with the class "class".

  • "#id" selects the element with the id "id".

  • first: Filters the selection to the first element of the matched set.

Example 1

In the following example, we are using the :first selector to select the first <p> element −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p:first").css("background-color", "yellow");
    })
});
</script>
</head>
<body>
   <p>This is the first paragraph.</p>
   <p>This is the second paragraph.</p>
   <p>This is the third paragraph.</p>
<button>Click</button>
</body>
</html>

When we click the button, the first paragraph element in the DOM will be highlighted with yellow background color.

Example 2

Here, we are selecting the first div element using :first selector −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("div:first").css("background-color", "yellow");
    })
});
</script>
</head>
<body>
   <div>This is the first div.</div>
   <div>This is the second div.</div>
   <div>This is the third div.</div>
<button>Click</button>
</body>
</html>

After clicking the button, the first element in the DOM will be selected.

Example 3

In this example, we are selecting the first element with class "highlight" using :first selector −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $(".highlight:first").css("background-color", "yellow");
    })
});
</script>
</head>
<body>
<p class="highlight">This is the FIRST paragraph.</p>
<p>This is a normal paragraph.</p>
<p class="highlight">This is another paragraph.</p>
<button>Click</button>
</body>
</html>

After executing the above program, it selects the first element with class "highlight" and highlights with yellow background color.

jquery_ref_selectors.htm
Advertisements