Element indexes and jQuery

Posted by Danny Herran on Aug 10, 2010 in Frontend | No comments

Once the DOM is structured by the browser, each element in our HTML page has an index relative to its parent. Retrieving an element’s index with jQuery is an easy task, and it is so useful that it can save you a couple of lines of code.

Lets put an example to illustrate this. Imagine we have two lists and I need that when I click one of the li in the first list, the li in the second list located in the exact same position (or index) should be colored to red.

<ul id="first">
    <li>Do this</li>
    <li>Do that</li>
    <li>Do everything</li>

<ul id="second">
    <li>Don't do this</li>
    <li>Dont' do that</li>
    <li>Dont' do anything</li>

And now the fun part:

$("ul#first > li").click(function(){
    var index = $("ul#first > li").index(this);
    $("ul#second > li:eq(" + index + ")").css("color", "red");

So, if I click on “Do that”, the text “Don’t do that” will turn red. What I am doing here is using the index of the first element to alter a property of the second element based on its index.

Don’t forget to read the official documentation for more information on this regard.