Doug Fir
Doug Fir

Reputation: 21232

queryselectorAll() with regex attribute selector

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.

Upvotes: 6

Views: 15125

Answers (1)

Al.G.
Al.G.

Reputation: 4387

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']

Upvotes: 17

Related Questions