Search code examples
jquerydom-traversal

How to find absolute index() with jQuery?


<nav>
    <section>
        <aside>
    <div class="findthis">111111</div>
    <div class="findthis">222222</div>
    <div class="findthis">333333</div>  
    <div class="findthis">444444</div>
        </aside>
    </section>
</nav>


$('.findthis').each( function(){
      var index = $(this).index()+1;
      $(this).append(" ( this element = "+index+" )")
});

this is working! (http://jsfiddle.net/3c5TZ/)

but.... when i do/insert more HTML-tags like this...

<nav>
    <section>
        <aside>
    <div class="findthis">111111</div>
            <h2><h2>
    <div class="findthis">222222</div>
            <span></span>
    <div class="findthis">333333</div>
            <b></b>                          
    <div class="findthis">444444</div>
        </aside>
    </section>
</nav>

it fails! (http://jsfiddle.net/3c5TZ/1/)

Any ideas?


Solution

  • Please consult the documentation of index(). In your example, jQuery cannot really know what kind of index you are looking for, relative to what?

    One way of doing this is providing the selector for .index():

    $('.findthis').each( function(){
          var index = $(this).index('.findthis')+1;
          $(this).append(" ( this element = "+index+" )")
    });
    

    jsFiddle Demo

    Another (in this case maybe more effective) way is to run index() on the whole collection, and pass the element as a parameter:

    var $collection = $('.findthis');
    $collection.each( function(){
          var index = $collection.index(this)+1;
          $(this).append(" ( this element = "+index+" )")
    });
    

    jsFiddle Demo