Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

queryselectorAll() with regex attribute selector

Tags:

javascript

var arr = [].slice.call(document.querySelectorAll("a[href*='pricing']"));

Returns an array with length 6.

var arr = [].slice.call(document.querySelectorAll("a[href*='tarification']"));

Also produces an array of length 6.

The context is a website with either English or French pages. Either of the two versions or arr will return 6 results on a given page while the other will produce an empty array.

I would like to dynamically account for this. So regardless if the user is on a French or English page I know that one or the other versions will return 6 elements. I could write an if() statement. But is there a neater, shorter way? I tried the following:

var arr = [].slice.call(document.querySelectorAll("a[href*='(tarification|pricing)']"));

But that also returned an empty array.

like image 253
Doug Fir Avatar asked Nov 14 '15 22:11

Doug Fir


People also ask

What does the querySelectorAll () method do?

The querySelectorAll() method in HTML is used to return a collection of an element's child elements that match a specified CSS selector(s), as a static NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers.

How does the querySelector () method differ from querySelectorAll ()?

The querySelector() method returns the first element that matches a CSS selector. To return all matches (not only the first), use the querySelectorAll() instead.

What is the difference between getElementsByClassName and querySelectorAll?

About the differences, there is an important one in the results between querySelectorAll and getElementsByClassName : the return value is different. querySelectorAll will return a static collection, while getElementsByClassName returns a live collection.


1 Answers

It's about css selectors, not regular expressions:

var arr = [].slice.call(document.querySelectorAll("a[href*='tarification'], a[href*='pricing']"));

The following selects all links with pricing or tarification in their href:

a[href*='tarification'], a[href*='pricing']
like image 195
Al.G. Avatar answered Oct 13 '22 00:10

Al.G.