Get an element by index in jQuery

You can use jQuery's .eq() method to get the element with a certain index.

$('ul li').eq(index).css({'background-color':'#343434'});

You can use the eq method or selector:

$('ul').find('li').eq(index).css({'background-color':'#343434'});

$(...)[index]      // gives you the DOM element at index
$(...).get(index)  // gives you the DOM element at index
$(...).eq(index)   // gives you the jQuery object of element at index

DOM objects don't have css function, use the last...

$('ul li').eq(index).css({'background-color':'#343434'});

docs:

.get(index) Returns: Element

  • Description: Retrieve the DOM elements matched by the jQuery object.
  • See: https://api.jquery.com/get/

.eq(index) Returns: jQuery

  • Description: Reduce the set of matched elements to the one at the specified index.
  • See: https://api.jquery.com/eq/

Tags:

Dom

Jquery

Get