JavaScript 下一个兄弟?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4051612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript next sibling?
提问by JasonS
Could someone show me how to loop through the anchor tags within a div and find the next sibling?
有人可以告诉我如何遍历 div 中的锚标记并找到下一个兄弟姐妹吗?
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?
如何遍历链接?我可以.nextSibling
用来查找下一个兄弟姐妹是否是 div 吗?
回答by Tim Down
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
.
nextSibling
DOM 节点的属性在所有浏览器中都能完美运行,并且完全符合您的预期。如果没有下一个兄弟,则返回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>
:
迭代 a NodeList
(这是getElementsByTagName
返回的内容)与使用标准for
循环迭代数组相同。以下将遍历链接并在每次找到下一个兄弟是 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:
请注意,在非 IE 浏览器中,HTML 中元素之间的空白被视为文本节点。在考虑每个链接的下一个兄弟节点是什么时,您可能希望忽略这些空白节点。以下将做到这一点:
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);
}
}
回答by Alex Rashkov
for(var i=0; i<links.length; i++) {
if (links[i].nextChild.nodeName=="DIV")
alert("This is a DIV")
}