当我单击跨度时,我想获得下一个 ul。我可以通过链接 nextSiblings 来做到这一点,但是如果我将来在跨度之后更新并添加更多标签,这将中断。最近似乎是一个不错的选择,但它只适用于祖先。
是否可以在不为每个实例创建唯一 ID 的情况下获取下一个标签?
<span class="dropdown">category<span>
<button>click</button>
<ul><li></li></ul>
最佳答案
您可以查看 .nextElementSibling
(仅返回元素, .nextSibling
也会返回在这种情况下不相关的文本节点)属性,直到您找到 <ul>
元素或直到没有更多的 sibling ( .nextElementSibling === null
)
一种可能的方式:
function findNextUnorderedList(ev) {
let currentElement = ev.target.nextElementSibling;
while (currentElement) {
if (currentElement.nodeName === "UL") {
currentElement.insertAdjacentHTML("beforeend", "<li>found!</li>");
break;
}
currentElement = currentElement.nextElementSibling;
}
}
工作示例:
function findNextUnorderedList(node) {
let currentElement = node.nextElementSibling;
while (currentElement) {
if (currentElement.nodeName === "UL") {
currentElement.insertAdjacentHTML("beforeend", "<li>found!</li>");
break;
}
currentElement = currentElement.nextElementSibling;
}
}
document.querySelector("button")
.addEventListener("click", function() {
findNextUnorderedList(this);
});
// add some placeholder elements
(() => document.querySelector("button").insertAdjacentHTML("afterend", Array.from({ length: Math.floor(Math.random() * 10 + 1)}, (_,i) => `<div>${i+1}</div>`).join("")))();
<span class="dropdown">category<span>
<button>click</button>
<ul></ul>
关于Javascript 最接近/下一个类型的兄弟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60170444/