Can I use a regular expression in querySelectorAll?

蓝咒 提交于 2019-11-26 11:00:53

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/16791527/can-i-use-a-regular-expression-in-queryselectorall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!