Can't find a "not equal" css attribute selector

Css

Css Problem Overview


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;
}

Css Solutions


Solution 1 - Css

Use the code like this:

div[foo]:not([foo=''])
{
    /* CSS Applied to divs having foo value Not nothing (or having a foo value assigned) */
}

Solution 2 - Css

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'])

Solution 3 - Css

:not([foo=''])
{
    background: red;
}

http://jsfiddle.net/gsLvuys0/

Solution 4 - Css

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> */
}

Solution 5 - Css

You can select the first one using

[foo = 'x']{
  background:red;
}

FIDDLE

Read this

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
QuestionAdrian RoscaView Question on Stackoverflow
Solution 1 - CssmehulmptView Answer on Stackoverflow
Solution 2 - CssmoomooView Answer on Stackoverflow
Solution 3 - CssCurtisView Answer on Stackoverflow
Solution 4 - Cssuser14550434View Answer on Stackoverflow
Solution 5 - CssSunil HariView Answer on Stackoverflow