Node.nextSibling & Node.previousSibling
Get the next and previous sibling node of an element, including nodes that aren’t elements (such as comments and text fragments).
<ul>
<!-- The gray wizard -->
<li>Gandalf</li>
<li>Radagast</li>
<li id="hermione">Hermione</li>
<!-- The surprise hero -->
<li>Neville</li>
</ul>
let hermione = document.querySelector('#hermione');
// returns <!-- The surprise hero -->
let next = hermione.nextSibling;
// returns <li>Radagast</li>
let previous = hermione.previousSibling;
⏰ Preorder my new course on Web Components! Want to learn how to build Web Components from scratch, master best practices, and more? Preorder today and get $100 off of the launch price.
Find this useful? You can support my work by purchasing an annual membership.