HTML:
Div 1
Div 2
Div 3
<
Easy fix - .each supports index :
$(".test").each(function(idx){
alert(idx);
});
You have to make it relative to what you're testing against. Use:
$(".test").each(function(){
var i = $('.test').index($(this));
console.log(i);
});
jsFiddle example
Per the docs on .index():
If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.
why the output is
4, 6, 8, 10
$(this).index()
returns the index of the element relative to its siblings, not to the selected elements. The br
and .divX
elements are siblings as well!
It looks like you want:
var $tests = $(".test");
$tests.each(function(){
var i = $tests.index(this);
alert(i);
});
or simpler:
$(".test").each(function(i){
alert(i);
});
What you want to do is this:
$(".test").each(function(i) {
alert(i);
});
.index() returns the index relative to its siblings.
index() gives index of element with respect to its siblings. The first div with class text is 5th element and has index 4, br is at 5 index and next div with class test has index 6 and so on. We can check the indexes of each element by the following demo
Live Demo
$("#parent1 *").each(function () {
alert("TagName >> " + this.tagName + ", Index >> " + $(this).index() + ", Text " + $(this).text());
});
If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements, Reference.