The jQuery first() method can be used to return the first item of the selected element. It selects the first inner item of the selected group element.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of these parameters is given below.
Parameter Name | Description |
---|---|
selector | Specify the group element to select its first item. You can use the element tag name, class name, or id to select. It is a required field. |
jQuery first() Method to Select First Element
If you want to select the first element of the selected element, you have to use the method as given below. You don’t have to use any parameter to use the method. After selecting the element, you can apply CSS using the css() of jQuery.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $("ul li").first().css("color","orange"); }); }); </script> <ul> <li>First Item</li> <li>Second Item</li> <li>Third Item</li> <li>Last Item</li> </ul> <button type="button" class="mybtn">Click to Select First</button> |
Output
- First Item
- Second Item
- Third Item
- Last Item
When you click the button given above, it selects the first list item that is present at a first position. The above example applies the orange color after selecting the first list item.
You may also like to read
I hope you like this tutorial on jQuery first() method. If you have any queries regarding the tutorial, please comment below.
References