128

I have an unordered list and the index of an li tag in that list. I have to get the li element by using that index and change its background color. Is this possible without looping the entire list? I mean, is there any method that could achieve this functionality?

Here is my code, which I believe would work...

<script type="text/javascript">
  var index = 3;
</script>

<ul>
    <li>India</li>
    <li>Indonesia</li>
    <li>China</li>
    <li>United States</li>
    <li>United Kingdom</li>
</ul>

<script type="text/javascript">
  // 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'});
</script>
informatik01
  • 16,038
  • 10
  • 74
  • 104
Rama Rao M
  • 2,961
  • 11
  • 44
  • 64
  • 3
    The two ways you're using there return dom elements rather than jQuery objects so the call to .css will not work on them. Darius' answer below using eq is what you want. – Richard Dalton Mar 27 '12 at 10:19

5 Answers5

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

isapir
  • 21,295
  • 13
  • 115
  • 116
gdoron
  • 147,333
  • 58
  • 291
  • 367
26

You can use jQuery's .eq() method to get the element with a certain index.

$('ul li').eq(index).css({'background-color':'#343434'});
Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
18

You can use the eq method or selector:

$('ul').find('li').eq(index).css({'background-color':'#343434'});
Darius
  • 10,762
  • 2
  • 29
  • 50
  • 1
    You could have make the selector simpler with `$('ul li').eq(index).css({'background-color':'#343434'});` – gdoron Mar 27 '12 at 10:33
  • 1
    But in most browsers the selector `$('ul').find('li')` is faster. [[1](http://stackoverflow.com/a/11503220/1293700), [2](https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/jquery4u/2013/04/jquery-parent-child-selectors.png)] – Darius May 23 '16 at 01:18
5

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.

Yury Fedorov
  • 14,508
  • 6
  • 50
  • 66
-1

You could skip the jquery and just use CSS style tagging:

 <ul>
 <li>India</li>
 <li>Indonesia</li>
 <li style="background-color:#343434;">China</li>
 <li>United States</li>
 <li>United Kingdom</li>
 </ul>
Adam H
  • 152
  • 9