gpt4 book ai didi

javascript - 如何查找当前选定 DOM 对象的所有 sibling

转载 作者:行者123 更新时间:2023-12-03 00:39:09 25 4
gpt4 key购买 nike

在 JavaScript 中查找所有 nextSiblings 和 previousSiblings 的完美方法是什么?我尝试了几种方法但没有得到准确的解决方案。如果选择任何元素,我需要获取所有下一个同级元素的长度,不包括空格、任何空格或换行符。

而且我不想为此使用 jQuery。我专门从 JavaScript 中寻找一些东西

最佳答案

这是一个有点啰嗦的解决方案,但允许您创建一个关于如何获取 sibling 的过滤器。

共有三个函数可以获取上一个、下一个或全部。如果您需要更多地控制要收集的 sibling 类型,这可以改进,但这是一个不错的起点。认为可能值得添加。

<强> Working Example

获取所有下一个 sibling

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

获取所有 previous sibling 姐妹

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

获取所有 sibling

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

关于javascript - 如何查找当前选定 DOM 对象的所有 sibling ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4378784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com