Skip to main content Accessibility Feedback

Traversing the DOM

Unless otherwise noted, these work in all modern browsers, and IE9+. You can extend support back further with polyfills.


Get the parent of an element.

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

You can also string them together to go several levels up.

var levelUpParent = elem.parentNode.parentNode;

Works back to at least IE6.


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.

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');


While querySelector() and querySelectorAll() search through all levels within a nested DOM/HTML structure, you may want to just get immediate descendant elements of a particular element. Use the .children property for this.

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


Works similar to .children, but also finds text fragments and other non-element nodes.

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

Works back to at least IE6.

Get sibling elements

getSiblings() is a helper method I wrote that gets the siblings of an element in the DOM. For example: if you had a list item (<li>) and wanted to grab all of the other items in the list.

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