šŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

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.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *