Skip to main content Accessibility Feedback

Traversing the DOM

Element.closest()

Get the closest parent up the DOM tree that matches against a selector.

The Element.closest() method starts with the element itself. You can start with the first parent element by pairing it with the Node.parentNode property.

<main>
	<div class="hero">
		<div id="app">
			<h1 data-sandwich>Hello, world!</h1>
		</div>
	</div>
</main>
let h1 = document.querySelector('h1');

// returns the .hero element
let hero = h1.closest('.hero');

// returns the h1 element itself
let sandwich = h1.closest('[data-sandwich]');

// Start with the element's parent
// returns null
let sandwich2 = h1.parentNode.closest('[data-sandwich]');

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.