I am trying to get the the first element with a specific class which follow the element clicked with pure JS (no JQuery) in the following way but get el.nextSibling is not a function error. Initially I was using JQuery parents().next() but would like to do this with pure JS:
const togglers = document.querySelectorAll('.toggler');
//console.log(togglers);
togglers.forEach(function(el) {
el.addEventListener('click', function(e) {
//const content = el.innerHTML;
//console.log(content);
el.nextSibling('.folder-content').style.display = 'block';
})
});
<div class="folder">
<div class="toggler">Click me 1</div>
<div class="folder-content" style="display: none">
Lorem ipsum
</div>
</div>
<div class="folder">
<div class="toggler">Click me 2</div>
<div class="folder-content" style="display: none">
Lorem ipsum
</div>
</div>
Any help would be appreciated :)
You can add a
while
loop to go searching for the firstnextSibling
that matches your criteria.edit: As @j08691 points out, if your real code only cares about elements and not other node types, you can use nextElementSibling.
nextElement
is a property, not a function, so you don't use()
with it. That said, usingnextSibling
can give you white space content which you don't want. Instead you can usenextElementSibling
:I was building this answer while the others were coming in and, in the interest of variety and neat DOM programming, here's another way to skin this cat:
Here is the initial code that you have provided with a call to a separate function to do what was requested(find the next sibling matching a specified query string)
You'll notice that the function I am providing is called
searchNextSiblings
and it takes three parameters:Here is the function itself:
And here is the annotated version: