I have a lot of the same elements on a page that is not under my direct control (so i can't change the HTML). This 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 elements with class item that have an id.
I can do
#brand_one, #brand_two, ... { color:red; }
But the id's go into the hundreds, so that's not an option.
What i'm looking for is a rule something like this:
.item[id] { color:red; } / .item# { color:red; }
I know this is possible in Javascript, but does this exist in CSS?
The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.
ID and class are two of the mostly used CSS selectors that not only help with building the layout of the HTML document but they also help with styling it.
In JavaScript, you can almost select any element from the DOM based on its unique ID by using the getElementById() method. It returns the first element that matches the given ID, or null if no matching element was found in the document.
Answer. As HTML and CSS are designed to be very fault tolerant, most browsers will in fact apply the specified styles to all elements given the same id. However, this is considered bad practice as it defies the W3C spec. Applying the same id to multiple elements is invalid HTML and should be avoided.
Yes, this is possible using CSS attribute selectors:
.item[id] {
/* any elements with a class .item and an ID attribute */
}
Yes, this exists. In you case you should use:
div[id*="brand"] { color: red; }
This selects all div
s with an id that contains brand
and colors it red.
Edit: You can also, to make sure it only targets id
s with brand_
in the start of the id
-name, use the following:
div[id^="brand_"] { color: red; }
This will avoid that other div
s in the future that have an id
that contains brand
will also be targeted.
Edit 2: To make it even MORE specific, you can target only id
s that are following the class="item"
:
div[id^="brand_"].item { color: red; }
This targets all div
s with brand_
in the beginning of the id
and have item
as a class
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With