How to scope your selectors in vanilla JS

You can use the native querySelector() and querySelectorAll() methods to get an element or set of elements from the DOM. But did you know you can scope these methods so they only search within a particular element?

You’ll most often use these methods on the Document interface, which means the JavaScript interpreter will search the entire document for your selection. To get the first form on the page, you might do this:

// Get the first form on the page
var form = document.querySelector("form");

But now let’s say you need to get all the controls within that form. Why search the entire document when you know they’re inside this element?

Thankfully, these selector methods are also available to the Element interface. To get all the controls inside the form, you can just call the querySelectorAll() method on the form itself:

// Get all the controls inside the form
var controls = form.querySelectorAll("input, textarea, select");

Note: if you’re new to vanilla JS and find it hard to give up jQuery’s selector syntax, my friend Chris Ferdinandi wrote two tiny helper functions you’ll appreciate: $.js and $$.js. They still allow you to scope your selectors.

If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!