Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a regular expression in querySelectorAll?

On a page I'm doing I will be ending up with custom link elements like this:

<link rel="multiply" type="service/math" src="path/to/service"> <link rel="substract" type="service/math" src="path/to/service"> ... 

I'm trying to use querySelectorAll to retrieve all link elements with a type service/... specified and am getting nowhere.

Currently I'm selecting this:

root.querySelectorAll('link'); 

which gives me all <link> elements when I only want the ones with type service/.*

Questions:
Can I add a regex to a QSA selector? If so, how to do it?

like image 917
frequent Avatar asked May 28 '13 12:05

frequent


People also ask

Can you use forEach on querySelectorAll?

Since nodeList selected by querySelectorAll has an array-like structure so you can directly apply forEach method with it and pass element as the first element in the callback function.

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.

What is the difference between getElementsByClassName and querySelectorAll?

querySelectorAll successfully removes the classes from all the elements, but getElementsByClassName only removes the classes from about half the elements.

What is the difference between querySelector and querySelectorAll?

Differences: As seen above, querySelector() methodcan only be used to access a single element while querySelectorAll() method can be used to access all elements which match with a specified CSS selector. To return all matches, querySelectorAll has to be used, while to return a single match, querySelector is used.


1 Answers

You can't really use a regular expression in a selector but CSS selectors are powerful enough for your need with a "starts with" syntax inspired by regexes.

You can use a substring matching attribute selectors : link[type^=service]

Reads "Nodes of type link with an attribute type starting with "service"

From the formal specification:

[att^=val]

Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.

Working JSFiddle

like image 160
Benjamin Gruenbaum Avatar answered Sep 23 '22 06:09

Benjamin Gruenbaum