Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The jQuery :eq(index) selector

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?

like image 373
chaonextdoor Avatar asked Jan 17 '23 20:01

chaonextdoor


1 Answers

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/

like image 145
iambriansreed Avatar answered Jan 31 '23 07:01

iambriansreed