当我单击span时,我想获得下一个ul。我可以通过链接nextSiblings来做到这一点,但是如果我在以后的跨度之后更新并添加更多标签,那将会中断。最接近的赌注似乎是个不错的选择,但它仅适用于祖先。
是否可以在不为每个实例创建唯一ID的情况下获取下一个标记?
<span class="dropdown">category<span>
<button>click</button>
<ul><li></li></ul>
答案 0 :(得分:2)
您可以检查.nextElementSibling
(仅返回元素,.nextSibling
还将返回在这种情况下不相关的文本节点)属性,直到找到<ul>
元素或直到不再有兄弟姐妹(.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>