如何让 CSS 选择以字符串开头的 ID(不是在 Javascript 中)?

2022-01-10 00:00:00 css-selectors html css

如果 HTML 有这样的元素:

If the HTML has elements like this:

id="product42"
id="product43"
...

如何匹配所有以产品"开头的 id?

How do I match all of those id's starting with "product"?

我已经看到完全使用 javascript 执行此操作的答案,但是如何仅使用 CSS 执行此操作?

I've seen answers that do this exactly using javascript, but how to do it with only CSS?

推荐答案

[id^=product]

^= 表示以"开头.反之,$= 表示以"结尾.

^= indicates "starts with". Conversely, $= indicates "ends with".

这些符号实际上是从 Regex 语法中借用的,其中 ^$ 分别表示字符串开头"和字符串结尾".

The symbols are actually borrowed from Regex syntax, where ^ and $ mean "start of string" and "end of string" respectively.

有关完整信息,请参阅规范.

See the specs for full information.

相关文章