Reputation: 449
Here is the example code:
<div>
<div>
</div>
<div>
</div>
<div>
</div>
....
</div>
I just need to find the index of the the inner div in the parent div, passed to function as this.
p.s. I checked the other question which is same: Is it possible to get element's numerical index in its parent node without looping?
however that method suggested did not work for me.. Is it possible to get element's numerical index in its parent node without looping?
Upvotes: 1
Views: 192
Reputation: 707148
Here's a working example using plain JS (no jQuery): http://jsfiddle.net/jfriend00/xgk4y/. Click on any of the divs to see the index returned from countPrevSiblings()
.
And the code from that:
function countPrevSiblings(elem) {
var i = 0;
while((elem = elem.previousSibling) != null) {
// count element nodes only
if (elem.nodeType == 1) {
++i;
}
}
return i;
}
Upvotes: 1