Last Updated on August 4, 2022 by Roshan Parihar
In this tutorial, learn how jQuery get first element of li on button click. The short answer is to use the :first
selector to find the first element of li in ul in jQuery.
There are many different ways given below that you can use to select the li item. After you select it, you can apply the CSS or any other effect to it.
So, let’s learn the different methods given below.
Method 1: Using nth-child() Selector to Get the First Element of li in jQuery
The method uses the jQuery nth-child()
selector where you have to put the position of the li item to select. It requires a numeric value as an argument to select the item. Here, you have to put 1 as the position of the first item of li in ul to select.
It uses the onclick event of jQuery to select the item when you click the button.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ $('button').click(function(){ $( "ul li:nth-child(1)" ).css( "color", "green" ); }); }); </script> <p><button type="button">Click Me</button></p> <ul> <li>1st list item</li> <li>2nd list item</li> <li>3rd list item</li> <li>4th list item</li> </ul> |
Output
- 1st list item
- 2nd list item
- 3rd list item
- 4th list item
Click the button given in the example above to select the first li item. It applies the ‘green’ color to the element after you click it.
Method 2: Using jQuery :first Selector to Find First li Element
It uses the jQuery :first
selector to select the first li item. The method requires no value as an argument to select the li first item. You have to use $("ul li:first")
in the code to get the start item of li.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ $('button').click(function(){ $( "ul li:first" ).css( "color", "yellow" ); }); }); </script> <p><button type="button">Click Me</button></p> <ul> <li>Top</li> <li>Bottom</li> <li>Left</li> <li>Right</li> </ul> |
Output
- Top
- Bottom
- Left
- Right
The above example applies the ‘yellow’ color to the first li item when you click the button. You can apply any other effect of jQuery after selecting the first li item.
Method 3: Using eq() Selector in jQuery to Select
The method uses the jQuery :eq()
selector to select the item equal to the given index value. The list items start with index 0 and you have to use this value to select the first li item.
You have to use $("ul li:eq()")
and put 0 as its argument to select the item. See the example given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ $('button').click(function(){ $( "ul li:eq(0)" ).css( "color", "red" ); }); }); </script> <p><button type="button">Click Me</button></p> <ul> <li>One</li> <li>Two</li> <li>Three</li> <li>Fore</li> </ul> |
Output
- One
- Two
- Three
- Fore
The above example selects the first li item of the list element on a button click. After selecting, it applies the ‘red’ color to the first li item.
You May Also Like to Read