Explain Codes LogoExplain Codes Logo

How to do a wildcard element name match with "querySelector()" or "querySelectorAll()" in JavaScript?

javascript
xpath
regex
wildcard-matching
Alex KataevbyAlex Kataev·Nov 1, 2024
TLDR

Fairly elemental, isn't it? Use CSS attribute selectors in querySelectorAll for wildcard matching:

let startsWithWildcard = document.querySelectorAll('[name^="data-"]'); // 'data-' centric, a 'solid' start! let containsWildcard = document.querySelectorAll('[name*="example"]'); // An 'example' for all! let endsWithWildcard = document.querySelectorAll('[name$="end"]'); // The 'end' of an era.

querySelector enables you to pattern-match with the name attribute, leveraging ^=, *=, $= for beginnings, middles, and ends of attribute values.

Flexibility with XPath and Regex: Extending wildcard matching

Simply gargantuan tasks require advanced tactics. Here, XPath and regular expressions come into play.

XPath: The old guard

XPath still comes in handy when you need to make wildcard matches that go beyond querySelectorAll.

// "data" night fever! Targeting elements with "data" anywhere in the name let xpathResult = document.evaluate("//*[contains(local-name(), 'data')]", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); // Array-nge! Converting XPathResult into an array of elements let elements = []; for (let i = 0; i < xpathResult.snapshotLength; i++) { elements.push(xpathResult.snapshotItem(i)); }

Avoid deprecated features because you care about compatibility, don't you?

NodeList to Array: Increasing versatility

The NodeList object from the querySelectorAll function is as flexible as a steel rod. Convert it to an Array:

let nodelist = document.querySelectorAll('...'); let elementsArray = Array.prototype.slice.call(nodelist); // Slice it like a pro!

Now you can unleash your inner mastery of array methods — sorting, filtering, iterating, the works!

Regex: The wildcard champion!

Unleash the full power of RegExp to target specific naming patterns. Level-up your anchor-tag hunting game:

let regex = /^data-/; // "data-" must conquer the world... Starting now! let matchingElements = elementsArray.filter(el => el.tagName.match(regex));

Taming attribute selectors

Cracking the nuances of attribute selectors enhances your handling of wildcard matches:

Matching Prefixes and Suffixes

CSS selectors stretch beyond simple containment checks and can spot attribute prefixes (^=) or suffixes ($=):

let idPrefixMatch = document.querySelectorAll('[id^="user-"]'); // 'User-' friendly! let typeSuffixMatch = document.querySelectorAll('[type$="-widget"]'); // Widgets galore!

Dot notation: A blessing for attributes

Ever faced attribute-settlement issues? You can pacify them with simple attribute access:

element.setAttribute('tag-name', element.tagName.toLowerCase()); let myElement = document.querySelector('[tag-name="my-custom-tag"]'); // Hands on the custom element

Fusion: Combining selection strategies

Inventive problem-solving thrives off combining diverse approaches. Blend attribute queries, XPath evaluation, and regex patterns for richer wildcard selection experiences.