Reputation: 22147
<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
Reputation: 251
$('.findthis').each( function(i){
$(this).append(" ( this element = "+i+" )")
});
Try this ...
Upvotes: -1
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) + " )")
});
Upvotes: 5
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
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
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+" )")
});
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+" )")
});
Upvotes: 4