我可以在querySelectorAll中使用正则表达式吗?

时间:2021-10-12 03:58:33

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.

我正在尝试使用querySelectorAll检索具有类型服务/…的所有链接元素。指定了,我什么也没得到。

Currently I'm selecting this:

目前我选择这个:

root.querySelectorAll('link');

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

当我只想要类型为service/.*的元素时,它会给我所有的 元素

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

问题:我可以在QSA选择器中添加regex吗?如果是的话,怎么做呢?

1 个解决方案

#1


38  

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.

您不能在选择器中使用正则表达式,但是CSS选择器非常强大,可以满足您的需要,它具有regexes启发的“以开始”语法。

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

您可以使用子串匹配属性选择器:链接(^ =服务类型)

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

读取“具有属性类型以“service”开头的类型链接的节点”

From the formal specification:

从正式的规范:

[att^=val]

(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.

表示具有att属性的元素,其值以前缀“val”开头。如果“val”是空字符串,则选择器不表示任何内容。

Working JSFiddle

#1


38  

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.

您不能在选择器中使用正则表达式,但是CSS选择器非常强大,可以满足您的需要,它具有regexes启发的“以开始”语法。

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

您可以使用子串匹配属性选择器:链接(^ =服务类型)

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

读取“具有属性类型以“service”开头的类型链接的节点”

From the formal specification:

从正式的规范:

[att^=val]

(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.

表示具有att属性的元素,其值以前缀“val”开头。如果“val”是空字符串,则选择器不表示任何内容。

Working JSFiddle