Skip to main content Accessibility Feedback

Traversing the DOM

Child elements by selector

The querySelector() and querySelectorAll() APIs aren’t limited to just running on the document. They can be run on any element to search only for elements inside of it.

var elem = document.querySelector('#some-elem');

// Find the first element inside `#some-elem` that has a `[data-snack]` attribute
var snack = elem.querySelector('[data-snack]');

// Get all divs inside `#some-elem`
var divs = elem.querySelectorAll('div');

Works in all modern browsers, and IE9+. You can extend support back further with polyfills.