这是一个有点啰嗦的解决方案,但允许您创建一个关于如何获取兄弟姐妹的过滤器。
可以得到三个函数only以前的,only接下来,或者all。如果您需要更多地控制要收集的兄弟姐妹类型,这可以改进,但这是一个不错的起点。认为可能值得添加。
工作示例 http://www.jsfiddle.net/subhaze/3CLgK/
获取所有下一个兄弟姐妹
//this will start from the current element and get all of the next siblings
function getNextSiblings(elem, filter) {
var sibs = [];
while (elem = elem.nextSibling) {
if (elem.nodeType === 3) continue; // text node
if (!filter || filter(elem)) sibs.push(elem);
}
return sibs;
}
获取所有以前的兄弟姐妹
//this will start from the current element and get all the previous siblings
function getPreviousSiblings(elem, filter) {
var sibs = [];
while (elem = elem.previousSibling) {
if (elem.nodeType === 3) continue; // text node
if (!filter || filter(elem)) sibs.push(elem);
}
return sibs;
}
获取所有兄弟姐妹
//this will start from the first child of the current element's parent and get all the siblings
function getAllSiblings(elem, filter) {
var sibs = [];
elem = elem.parentNode.firstChild;
do {
if (elem.nodeType === 3) continue; // text node
if (!filter || filter(elem)) sibs.push(elem);
} while (elem = elem.nextSibling)
return sibs;
}
应用于上述函数的示例过滤器
// Example filter only counts divs and spans but could be made more complex
function exampleFilter(elem) {
switch (elem.nodeName.toUpperCase()) {
case 'DIV':
return true;
case 'SPAN':
return true;
default:
return false;
}
}
HTML 和测试输出
HTML
<div id='test'>
<div id='test2'>asdf</div>
<br /> sdf
<div>asdfasdf<span>asdf</span></div>
<div>a</div>
<span>a</span>
<br />
<div>d</div>
<hr/>
</div>
JavaScript
var elem;
elem = document.getElementById('test2');
//with filter alerts 4
alert( getNextSiblings( elem, exampleFilter ).length );
// no filter, alerts 7
elem = document.getElementById('test2');// put elem back to what it was
alert( getNextSiblings( elem ).length );
// alerts 0
elem = document.getElementById('test2');// put elem back to what it was
alert( getPreviousSiblings( elem, exampleFilter ).length );
// alerts 5
elem = document.getElementById('test2');// put elem back to what it was
alert( getAllSiblings( elem, exampleFilter ).length );