The nextSibling
property of DOM nodes works perfectly in all browsers and does exactly what you'd expect. If there is no next sibling, it returns null
.
Iterating over a NodeList
(which is what getElementsByTagName
returns) is identical to iterating over an array. The following will iterate over the links and alert each time it finds one whose next sibling is a <div>
:
var menu = document.getElementById('menu');
var links = menu.getElementsByTagName('a');
// Iterate over the links
for (var i = 0, len = links.length, link; i < len; ++i) {
link = links[i];
if (link.nextSibling && link.nextSibling.nodeName == "DIV") {
alert("Next sibling is DIV! " + link.innerHTML);
}
}
Note that in non-IE browsers, whitespace between elements in HTML is considered a text node. You may want to ignore these whitespace nodes when considering what the next sibling of each link is. The following will do that:
function isWhitespace(node) {
return node.nodeType == 3 && /^\s*$/.test(node.data);
}
// Iterate over the links
for (var i = 0, len = links.length, link, next; i < len; ++i) {
link = links[i];
next = link.nextSibling;
if (next && isWhitespace(next)) {
next = next.nextSibling;
}
if (next && next.nodeName == "DIV") {
alert("Next sibling is DIV! " + link.innerHTML);
}
}