Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript next sibling?

Tags:

javascript

dom

Could someone show me how to loop through the anchor tags within a div and find the next sibling?

I have this so far.

var menu = document.getElementById('menu');
var links = menu.getElementsByTagName('a');

How do I loop through the links? Can I use .nextSibling to find if the next sibling is a div?

like image 534
JasonS Avatar asked Oct 29 '10 12:10

JasonS


People also ask

What is next sibling in Javascript?

The read-only nextSibling property of the Node interface returns the node immediately following the specified one in their parent's childNodes , or returns null if the specified node is the last child in the parent element.

What is the nextSibling Is it a Javascript command what is its purpose?

nextSibling returns the next node (an element node, a text node or a comment node). Whitespace between elements are also text nodes. nextElementSibling returns the next element (not text and comment nodes).


1 Answers

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 using a standard for loop. 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);
    }
}
like image 153
Tim Down Avatar answered Oct 21 '22 23:10

Tim Down