Can CSS find an element with ANY ID?
I have a lot of the same elements on a page that is not under my direct control (so I cannot change the HTML). It might look like this:
<div class="item">This text should be black</div>
<div class="item" id="brand_one">This text should be red</div>
<div class="item" id="brand_two">This text should be red</div>
...
<div class="item">This text should be black</div>
I want to write a css rule that targets all items with an item class with an id.
I can do
#brand_one, #brand_two, ... { color:red; }
But id goes to hundreds, so not an option.
What I'm looking for is a rule like this:
.item[id] { color:red; } / .item# { color:red; }
I know this is possible in Javascript, but does it exist in CSS?
source to share
Yes, this is possible with CSS attribute selectors :
.item[id] {
/* any elements with a class .item and an ID attribute */
}
source to share
Yes, it does exist. In this case, you should use:
div[id*="brand"] { color: red; }
This selects everything div
with an ID that contains brand
and colors it red.
Edit: you can also make sure it only targets id
at brand_
the beginning of id
-name, use the following:
div[id^="brand_"] { color: red; }
This will avoid that others div
in the future who have id
that contain brand
will also be targeted.
Edit 2: To make it even more specific, you can only target the id
following class="item"
:
div[id^="brand_"].item { color: red; }
It points to everything div
with brand_
at the beginning id
and has item
how class
.
source to share
You can try using the css attribute selector:
div.item {
color: black;
}
div.item[id^='brand_'] {
color: red;
}
div.code {
text-transform: uppercase;
}
div.code[id^='brand_'] {
color: blue;
}
<div class="item">This text should be black</div>
<div class="item" id="brand_one">This text should be red</div>
<div class="item" id="brand_two">This text should be red</div>
<div class="item">This text should be black</div>
<div class="code">This text should be in caps</div>
<div class="code" id="brand_three">This text should be in caps and blue color</div>
Here [id^='brand_']
refers to id
starting with brand_
. There are also expressions $
(ends) and *
(contains).
source to share