In order to get the element you want, you need a function (see nextSibling
below), that can get you the next element matching a given selector, if present.
Code:
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;
}
The above function can be used as follows inside a click event handler:
nextSibling(this, "ul.lvl--2");
Check out the following snippet for a working example.
Snippet:
/* ----- 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>