151

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;
}
Adrian Rosca
  • 6,922
  • 9
  • 40
  • 57

5 Answers5

265

Use the code like this:

div[foo]:not([foo=''])
{
    /* CSS Applied to divs having foo value Not nothing (or having a foo value assigned) */
}
Vahid
  • 6,639
  • 5
  • 37
  • 61
mehulmpt
  • 15,861
  • 12
  • 48
  • 88
28

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'])
Lee Goddard
  • 10,680
  • 4
  • 46
  • 63
moomoo
  • 826
  • 10
  • 9
19
:not([foo=''])
{
    background: red;
}

http://jsfiddle.net/gsLvuys0/

Curtis
  • 101,612
  • 66
  • 270
  • 352
5

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

You can select the first one using

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

FIDDLE

Read this

Sunil Hari
  • 1,716
  • 1
  • 12
  • 20
  • Suppose there are 100 divs out of which foo value is absent(foo='') for 50 divs and other 50 divs have different foo value say foo=x or y etc then you need to write 50 selectors if we follow above solution – Shoaib Chikate Aug 13 '14 at 13:23
  • 2
    That is not the op wants :"I want to target only the first of the following divs with a css attribute selector" – Sunil Hari Aug 13 '14 at 13:24
  • Your answer is right with his requirement but not a general solution which other people have given. – Shoaib Chikate Aug 13 '14 at 13:27
  • @ShoaibChikate You're correct. I want the more generic solution. I updated the question to reflect that. – Adrian Rosca Aug 13 '14 at 13:48