53

I would like to select an element based on a substring of href attribute.

I posted a question recently where I received an answer based on "starts with":

document.querySelector('#utility-menu a[href^="/email_check?lang="').textContent.trim();

But actually, the only constant from page to page will be "lang=" within the href attribute. So /email_check? is page specific so I cannot use this variable on al pages.

Is it possible to modify my selector to return the textContent of any <a> element with the substring "lang=" within it?

0

2 Answers 2

93

All CSS selectors are documented on MDN and specified in the W3C CSSWG Selectors Level 4 overview1 (Archived link).

The one you need is

#utility-menu a[href*="lang="]
Pattern Represents
E[foo*="bar"] An E element whose foo attribute value contains the substring bar.

1: The CSSWG’s current work of the CSS Selectors Module is Selectors Level 4. Not all of its features are supported in all browsers. The Level 4 draft includes everything from Level 1 to Level 4. Watch the “Level” table column. Today’s browsers support at least up to Level 3, but check the compatibility tables on MDN to be sure.

0
16

Consider the following HTML element:

<div id="utility-menu">
  <a href="/email_check?lang=en-US">Hello, world!</a>
</div>

You can obtain the first anchor element that has a href attribute containing 'lang=' and exists as a descendant of an element with an id equivalent to 'utility-menu' using one of the following options:

// Using the [attr*=value] selector (best option)
document.querySelector('#utility-menu a[href*="lang="]')

// Using the find() method (alternative option)
[...document.querySelectorAll('#utility-menu a[href]')].find(e => e.href.includes('lang='))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.