Question

<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?

Was it helpful?

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

OTHER TIPS

The index is passed to the .each() method you don't have to reinvent the wheel:

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

Updated fiddle.

You have accidentally nested elements inside each other.

Change this:

<h2><h2>

to this:

<h2></h2>

Then it works just fine. Demo: http://jsfiddle.net/Guffa/3c5TZ/14/

use .index('.findthis') to constrain the counting only inside the list of .findthis items.

demo at http://jsfiddle.net/3c5TZ/5/

also fixed the missing </h2> bug

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

Try this ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top