Get an element by index in jQuery


Jquery Problem Overview

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;

	<li>United States</li>
	<li>United Kingdom</li>

<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'});

Jquery Solutions

Solution 1 - Jquery

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

Solution 2 - Jquery

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

$('ul li').eq(index).css({'background-color':'#343434'});

Solution 3 - Jquery

You can use the eq method or selector:


Solution 4 - Jquery

There is another way of getting an element by index in jQuery using CSS :nth-of-type pseudo-class:

	// css selector that describes what you need:
	// ul li:nth-of-type(3)
	var selector = 'ul li:nth-of-type(' + index + ')';

There are other selectors that you may use with jQuery to match any element that you need.

Solution 5 - Jquery

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

 <li style="background-color:#343434;">China</li>
 <li>United States</li>
 <li>United Kingdom</li>


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRama Rao MView Question on Stackoverflow
Solution 1 - Jquerygdoron is supporting MonicaView Answer on Stackoverflow
Solution 2 - JqueryChristofer EliassonView Answer on Stackoverflow
Solution 3 - JqueryDariusView Answer on Stackoverflow
Solution 4 - JqueryYury FedorovView Answer on Stackoverflow
Solution 5 - JqueryAdam HView Answer on Stackoverflow