Using multiple selectors with JavaScript selector methods
One of my favorite vanilla JS “tricks” is that you can pass multiple selectors into JavaScript selector methods like Element.querySelector()
, Element.querySelectorAll()
, Element.closest()
, and Element.matches()
.
Because these methods accepts any valid CSS selector, you can use a comma-separated list of selectors to look for or match multiple selectors.
For example, let’s say you wanted to find all of the elements with the [data-toggle]
and [data-content]
attributes. You can pass them into the Element.querySelectorAll()
method like this…
// Get all matching elements
let elems = document.querySelectorAll('[data-toggle], [data-content]');
Want to find the first element with either the #sandwich
ID or the .tuna
class? Pass them both in to the Element.querySelector()
method…
// Get the first matching element
let sandwich = document.querySelector('#sandwich, .tuna');
This is particularly useful with the Element.matches()
method. You can use it to check if an element has one of a handful of selectors on it with a single check.
// Runs on a click event
function eventHandler (event) {
if (event.target.matches('#sandwich, .tuna, .mayo')) {
console.log(`It's a sandwich!`);
}
}