How to get CSS to select ID that begins with a string (not in Javascript)?

HtmlCssCss Selectors

Html Problem Overview


If the HTML has elements like this:

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

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

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

Html Solutions


Solution 1 - Html

[id^=product]

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

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.

Solution 2 - Html

I'd do it like this:

[id^="product"] {
  ...
}

Ideally, use a class. This is what classes are for:

<div id="product176" class="product"></div>
<div id="product177" class="product"></div>
<div id="product178" class="product"></div>

And now the selector becomes:

.product {
  ...
}

Solution 3 - Html

Use the attribute selector

[id^=product]{property:value}

Solution 4 - Html

I want to share this solution too, maybe in the future it could help someone.
As the others said you can write [id^=product] for id

But we can give an example for the class as well: [class^="product-"] which indicates classes starts with product and also * like this [class*="product-"]

This is a simple example :

/* Icons */
[class^="icon-"], [class*=" icon-"] {
  /* use !important to prevent issues with browser extensions that change fonts */
  font-family: 'mk-font' !important;
  font-size: 3em;
}

good luck ...

Solution 5 - Html

I noticed that there is another CSS selector that does the same thing . The syntax is as follows :

[id|="name_id"]

This will select all elements ID which begins with the word enclosed in double quotes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionabc123View Question on Stackoverflow
Solution 1 - HtmlNiet the Dark AbsolView Answer on Stackoverflow
Solution 2 - HtmlBlenderView Answer on Stackoverflow
Solution 3 - HtmlMusaView Answer on Stackoverflow
Solution 4 - HtmlFreemanView Answer on Stackoverflow
Solution 5 - HtmlLuigi SpeziaView Answer on Stackoverflow