Skip to main content Accessibility Feedback

Traversing the DOM

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).

	<!-- The gray wizard -->
	<li id="hermione">Hermione</li>
	<!-- The surprise hero -->
let hermione = document.querySelector('#hermione');

// returns <!-- The surprise hero -->
let next = hermione.nextSibling;

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

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