Reputation: 35
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.
Upvotes: 2
Views: 2841
Reputation: 2938
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;
}
Upvotes: 0
Reputation: 14746
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;
}
}
Upvotes: 0
Reputation: 43
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;
}
}
}
Upvotes: 0
Reputation: 11327
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);
Upvotes: 1