I want to target div elements where the attribute "foo" has a value.
<div foo="x">XXX</div>
<div foo="">YYY</div>
I have tried this css, but it doesn't work:
[foo!='']
{
background: red;
}
I want to target div elements where the attribute "foo" has a value.
<div foo="x">XXX</div>
<div foo="">YYY</div>
I have tried this css, but it doesn't work:
[foo!='']
{
background: red;
}
One problem with the accepted answer is that it will also select elements that do not have a foo
attribute at all. Consider:
<div>No foo</div>
<div foo="">Empty foo</div>
<div foo="x">XXX</div>
<div foo="y">YYY</div>
<div foo="z">ZZZ</div>
div:not([foo=''])
will select both the first and second div
elements. If you only want div
elements that have an attribute foo that is set to an empty string, you should use:
div[foo]:not([foo=''])
If you want all elements with attribute foo
that is neither y
nor z
, you should use:
div[foo]:not([foo='y']):not([foo='z'])
BTW if you are trying to select all elements with a certain attribute except for ones with the specific value, you could do something like this:
[data-foo]:not([data-foo="foo"]) {
/* matches <div data-foo="bar"> but not <div data-foo="foo"> or <div> */
}