Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an element by index in jQuery

Tags:

jquery

dom

get

People also ask

How do you select an element by index?

The :eq() selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). This is mostly used together with another selector to select a specifically indexed element in a group (like in the example above).

What is the difference between EQ () and get () methods in jQuery?

eq() returns it as a jQuery object, meaning the DOM element is wrapped in the jQuery wrapper, which means that it accepts jQuery functions. . get() returns an array of raw DOM elements. You may manipulate each of them by accessing its attributes and invoking its functions as you would on a raw DOM element.

What does .EQ do in jQuery?

eq() method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.

What is indexOf in jQuery?

The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.


$(...)[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/

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'});

There is another way of getting an element by index in jQuery using CSS :nth-of-type pseudo-class:

<script>
    // css selector that describes what you need:
    // ul li:nth-of-type(3)
    var selector = 'ul li:nth-of-type(' + index + ')';
    $(selector).css({'background-color':'#343434'});
</script>

There are other selectors that you may use with jQuery to match any element that you need.