šŸ“• Build AI Agents using LangGraph.js is now out!

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.

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

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