Last Updated on February 15, 2021 by Roshan Parihar
In this tutorial, learn how to get second child element of list in jQuery. The short answer is: use the jQuery nth-child()
selector to select the second child item.
You can also use the jQuery eq()
method to select the second item of the list element. Let’s find out with the examples given below.
How to Get Second Child Element of List Using jQuery nth-child() Method
To get the second child element of the list, you have to use the nth-child()
selector with an argument as the location of the list element. To select the 2nd element of the list on button click, you have to use 2 as its argument value as given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ $('.mylibtn').click(function(){ $( "ul.mylione li:nth-child(2)" ).css( "color", "orange" ); }); }); </script> <ul class="mylione"> <li>1st Position item</li> <li>2nd Position item</li> <li>3rd Position item</li> <li>4th Position item</li> </ul> <button type="button" class="mylibtn">Click Me</button> |
Output
- 1st Position item
- 2nd Position item
- 3rd Position item
- 4th Position item
The above example contains the button and the list elements with 4 items. When you click the button given above, it selects the 2nd element and applies the ‘orange’ color to it that indicated the selected element.
Using jQuery eq() Selector to Select the Exact Element
To select the 2nd element using jQuery :eq()
selector, you have to specify index value as 1 as the index position of the second element is 1. See the example given below to get the required item:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ $('.mylibtntwo').click(function(){ $( "ul.mylitwo li:eq(1)" ).css( "color", "red" ); }); }); </script> <ul class="mylitwo"> <li>Left</li> <li>Right</li> <li>Top</li> <li>Bottom</li> </ul> <button type="button" class="mylibtntwo">Click Me</button> |
Output
- Left
- Right
- Top
- Bottom
When you click the button element given above to get the second item of the list element. After getting the required item, it applies the ‘red’ color to it.
You May Also Like to Read