Skip to main content Accessibility Feedback

Traversing the DOM

Element.closest()

Get the closest parent up the DOM tree that matches against a selector. It also checks the element itself.

var elem = document.querySelector('#some-elem');
var closestSandwich = elem.closest('[data-sandwich]');

Implemented with vendor prefixes in a handful of browsers. Use with a polyfill.