JavaScript下一个兄弟姐妹? [英] JavaScript next sibling?

查看:87
本文介绍了JavaScript下一个兄弟姐妹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人告诉我如何循环通过div中的锚标签,找到下一个兄弟姐妹?



我有这个目的。

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

如何循环浏览链接?我可以使用 .nextSibling 来查找下一个兄弟姐妹是否是一个div?

解决方案

DOM节点的 nextSibling 属性在所有浏览器中都能完美运行,并且完全符合您的期望。如果没有下一个兄弟姐妹,它将返回 null



迭代 NodeList (这是什么 getElementsByTagName 返回)与使用的标准循环。以下内容将遍历链接,并在每次找到下一个兄弟姐妹是< div> 时发出警告:

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

//迭代链接
for(var i = 0,len = links.length,link; i< len; ++ i){
link = links [一世];
if(link.nextSibling&&&link; nextSibling.nodeName ==DIV){
alert(Next sibling is DIV!+ link.innerHTML);
}
}

请注意,在非IE浏览器中,元素之间的空格在HTML中被认为是一个文本节点。当考虑每个链接的下一个兄弟节点时,您可能想忽略这些空白节点。以下将这样做:

  function isWhitespace(node){
return node.nodeType == 3&& ; /^\s*$/.test(node.data);
}

//迭代链接
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);
}
}


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?

解决方案

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);
    }
}

这篇关于JavaScript下一个兄弟姐妹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆