ysakiyev
ysakiyev

Reputation: 449

How to determine the index of the element in its parent node?

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

Answers (2)

jfriend00
jfriend00

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

Riz
Riz

Reputation: 10236

You can get index by using index() jquery function, if this is not working for you, explain you question bit more.

Sample : $(this).index($(this).siblings());

Upvotes: 0

Related Questions