Rama Rao M Rama Rao M - 10 months ago 55
jQuery Question

Get an element by index in jquery

I have an un ordered list and the index of li tag.Now I have to get the li elemet by using that index and change background color.Is it possible without looping entire list?.I mean, Is ther any method that could achieve this functionality?

Here is my code, which I belive that would work...

var index = 3;
<li>United States</li>
<li>United Kingdom</li>
//I want to change bgColor of selected li element
$('ul li')[index].css({'background-color':'#343434'});
//Or, I have seen a function in Jquery doc, which gives nothing to me
$('ul li').get(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'});


.get([index]) Returns: Element

.eq(index) Returns: jQuery