为了获得您想要的元素,您需要一个函数(见nextSibling
下文),它可以让您获得与给定选择器匹配的下一个元素(如果存在)。
代码:
function nextSibling (element, selector) {
/* Check whether a selector is given. */
if (selector) {
var
/* Cache the children of the parent and the index of the element in them. */
family = element.parentNode.children,
index = [].indexOf.call(family, element),
/* Find the elements with greater index that match the given selector. */
siblings = [].filter.call(family, (e, i) => e.matches(selector) && i > index);
return siblings[0];
}
else return element.nextElementSibling;
}
上述函数可以在 click 事件处理程序中按如下方式使用:
nextSibling(this, "ul.lvl--2");
查看以下代码片段以获取工作示例。
片段:
/* ----- JavaScript ----- */
function nextSibling (element, selector) {
/* Check whether a selector is given. */
if (selector) {
var
/* Cache the children of the parent and the index of the element them. */
family = element.parentNode.children,
index = [].indexOf.call(family, element),
/* Find the elements with greater index that match the given selector. */
siblings = [].filter.call(family, (e, i) => e.matches(selector) && i > index);
return siblings[0];
}
else return element.nextElementSibling;
}
document.getElementById("span").onclick = function() {
console.log(nextSibling(this, "ul.lvl--2"));
}
<!----- HTML ----->
<ul class="lvl--1">
<li>Link 1</li>
<li>
<span>Link 2</span>
<button>
chevron_down
</button>
<ul class="lvl--2" alt="NOT THIS UL">
<li>Sub Link 1</li>
</ul>
</li>
<li>Link 3</li>
</ul>
<ul class="lvl--1">
<li>Link 1</li>
<li>
<span id = "span" alt="CLICK HERE">Link 2 (CLICK)</span>
<button>
chevron_down
</button>
<ul class="lvl--2" alt="SELECT THIS">
<li>Sub Link 1</li>
</ul>
</li>
<li>Link 3</li>
</ul>