On Twitter, Kabolobari asked me how to climb down the DOM.
Matching by selector #
querySelectorAll methods are typically used on the document to get all matching elements on a page.
var elem = document.querySelectorAll('.some-selector');
But, you can also use them to search within a particular element rather than just the whole document. You can, for example, find an element with the
.pick-me class, and then search within that element to find another element with the
var pickMe = document.querySelector('.pick-me'); var andMe = pickMe.querySelector('.and-me');
This will only look for
.and-me inside your
You can similarly use
querySelectorAll() to get all matching elements inside the element.
var pickMe = document.querySelector('.pick-me'); var meToo = pickMe.querySelectorAll('.me-too');
Only match direct decendants #
querySelectorAll methods search within all sub-elements of the parent element.
<div class="parent"> <div class="sub-element-1">...</div> <div class="sub-element-2"> ... <div class="sub-element-2a">...</div> <div class="sub-element-2b">...</div> </div> <div class="sub-element-3">...</div> </div>
In the example above, if you used
querySelectorAll on the
.parent element, they would search all the way down into
If you only want to search direct descendants, you can use the
var parent = document.querySelector('.parent'); var directDecendants = parent.childNodes;
That would only return