Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Javascript – use querySelectorAll() with wildcards

The querySelectorAll() consolidated all the methods such as getElementById(), getElementsByTagName() or getElementsByClassName() into just one single universal tool. It became the ultimate selector method!

While working on the React pin input component I've discovered you can also use querySelectorAll() with wildcards:

// will select all the elements whose id starts with  "digit"
let digits = document.querySelectorAll('[id^="digit"]')

digits.forEach(digit => {
  // so stuff here
});

As with the case of the attribute selector we can do different types of wildcards:

  • querySelectorAll('[id~="digit"]'): checks if the id contains the string "digit" no matter the position
  • querySelectorAll('[id^="digit"]'): checks if the id starts with the '"digit"' string
  • querySelectorAll('[id$="digit"]'): checks if the id ends with the '"digit"' string

Using querySelectorAll() wildcards with multiple values

And even more, we can use the querySelectorAll() wildcards with multiple values:

document.querySelectorAll(`[id^="digit"], [id^="test"]`);

For example, the above code will select all the elements whose id starts with one of the "digit" or "test" strings.

Using querySelectorAll() with case insensitive values

By default querySelectorAll() is case-sensitive. Therefore if we apply:

document.querySelectorAll('[id^="digit"]')

To this html:

<div id="digit-1"></div>
<div id="digit-2"></div>
<div id="DIGIT-3"></div>

We will get only 2 results back, the elements for "digit-1" and "digit-2".

If we want to select all the values as case insensitive we can add the i flag:

document.querySelectorAll('[id^="digit" i]')

As a closing thought, even if querySelectorAll() is great, and with wildcards, it becomes an even better tool just don't use to use querySelectorAll() in React components.

Home Screencasts Best of Newsletter Search X