I want to use the jQuery :eq(index) selector dynamically, which means I want to supply a variable as the index and choose the corresponding element dynamically. But it seems that it doesn't work. I think it's because the quotation marks. As this selector is used as, for example, $('ul li:eq(3)'), when I provide a variable as the index, maybe the index is viewed as a part of the string in the selector instead of a variable. Is it right? How can I fix this and choose the element dynamically?
var index = 5;
The following would work in your example.
$('ul li:eq(' + index + ')')
But for better performance in modern browsers, use:
$('ul li').eq(index)
Another reason .eq()
is better than :eq()
is you can pass '.eq(-1)' to get the last element.
Source: http://api.jquery.com/eq-selector/
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