l2aelba
l2aelba

Reputation: 22147

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?

Upvotes: 3

Views: 459

Answers (5)

Avi
Avi

Reputation: 251

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

Try this ...

Upvotes: -1

Shadow Wizard
Shadow Wizard

Reputation: 66389

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.

Upvotes: 5

Guffa
Guffa

Reputation: 700152

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/

Upvotes: 3

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195962

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

Upvotes: 1

kapa
kapa

Reputation: 78671

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

Upvotes: 4

Related Questions