Tuesday, September 4, 2007

Get the previous sibling of a node

Consider this DOM tree:

<book>
<title>Magic Mayhem</title>
<author>Merlin</author>
<publisher>King Arthur Inc.</publisher>
</book>

and you would like to know who is the TITLE of the book, by passing the AUTHOR node to a function, i.e: getSibling(node); . You may use a handy function called element.previousSibling but there is matters to consider.

Must use a loop
The correct way (in IE & Mozilla) to get the previous sibling of a certain node is by using a loop that iterates through the child nodes:

function get_previoussibling(n)
{
//n = <author>
var x=n.previousSibling;
while (x.nodeType!=1)
{
x=x.previousSibling;
}
return x;
}

The nodeType = 1 will only be TRUE if the element is an element node (not a textnode or any other nodes). So the loop will keep on iterating until it find the correct element node (<title>) and returns that node. However, this may requires hevery processing when we have thousands of child nodes. Hence, if you are sure and know where is the place [index] of the child node you want, you may try this instead:

//n = <author>
var prevSibling = document.getElementById(n).parentNode.childNodes[0]; //returns <title> --- no loops required.

ref:
http://www.w3schools.com/dom/prop_element_previoussibling.asp

No comments: