Skip to main content Accessibility Feedback

Traversing the DOM

Element.nextElementSibling & Element.previousElementSibling

Get the next and previous sibling element of an element.

<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 <li>Neville</li>
let next = hermione.nextElementSibling;

// returns <li>Radagast</li>
let previous = hermione.previousElementSibling;

Find this useful? You can support my work by purchasing an annual membership.