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).
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.
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.
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
.eq(index)
Returns: 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'});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With