How jQuery Get First Element of li Using Selectors

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.

Test it Live

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.

Test it Live

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.

Test it Live

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