2

Supposing you have:

<div><p>Some text</p><p>Some text</p></div>
<div><p id='paragraph'>Some text</p></div>

How can you use javascript to find the index of the parent node of id 'paragraph'? I think you have to loop through, with 'docment.getElementsByTagName('div'), but I'm stuck after that. Thanks for any advice.

1
  • If you need the index of a HTML element inside its parent, you're doing something wrong... The DOM doesn't work like that. (It might, but don't make it.) Commented May 14, 2011 at 0:07

4 Answers 4

1

I assume you only want to include elements in the index.

var node = document.getElementById('paragraph').parentNode,
    i = 0;

while( node = node.previousSibling ) {
    if( node.nodeType === 1 ) {
        i++;
    }
}

alert(i);

http://jsfiddle.net/dJd6g/

Sign up to request clarification or add additional context in comments.

2 Comments

No point in the ===. It's always a number. Save the === for when they're useful.
@Rudie: I prefer to standardize my code with === and save the == for when it's useful (which is rare). Just my preference. :)
0

if markup's structure remains the same you could do something like this:

var parents = document.getElementsByTagName('div');
for(var i=0, length = parents.length, found = false; i < length && !found; i++){
  var parent = parents[i];
  if(parent.querySelector('#paragraph')){//or search for child with that id if IE < 8
    alert('index is '+i);
    found = true;
  }
}

Comments

0

I lightly tested this and it should work on most browsers (not sure about IE):

var parentIndex = function (id)
{
    var elm = document.getElementById(id);
    var par = elm.parentNode;
    var sib = par.parentNode.childNodes;

    for (var i = 0; i < sib.length; i++)
    {
        if (par == sib[i])
        {
            return i;
        }
    }
}

Comments

0

To follow the standard of -1 being no match -

function indexOf(element) {
    var index = -1;
    while (element) {
        element = element.previousSibling;
        if (element.nodeType === 1) {
            index++;
        }
    }
    return index;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.