Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use an attribute selector for CONTAINS in queryselector()?

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?

like image 984
Doug Fir Avatar asked Aug 02 '15 15:08

Doug Fir


People also ask

How do I use type attribute in querySelector?

You can use querySelectorAll() like this: var test = document. querySelectorAll('input[value][type="checkbox"]:not([value=""])');

How do I get attributes from querySelector?

How it works: First, select the link element with the id js using the querySelector() method. Second, get the target attribute of the link by calling the getAttribute() of the selected link element. Third, show the value of the target on the Console window.

Can you select multiple elements with querySelector?

Yes, because querySelectorAll accepts full CSS selectors, and CSS has the concept of selector groups, which lets you specify more than one unrelated selector.


1 Answers

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.

like image 153
Sebastian Simon Avatar answered Sep 20 '22 12:09

Sebastian Simon