Select an Element with a Non-Empty Attribute

Avatar of Chris Coyier
Chris Coyier on (Updated on )

Short answer:

[data-foo]:not([data-foo=""]) { }

Longer answer (same conclusion, just an explanation on why we might need this):

Say you have an element that you style with a special data-attribute:

<div data-highlight="product">
</div>

You want to target that element and do special things when highlighting.

[data-highlight] {
  font-size: 125%; 
}

[data-highlight="product"] img {
  order: 1;
}

That data-type attribute is part of a template, so it can have any value you set.

<div data-highlight="{{ value }}">
</div>

And sometimes there is no value! So the output HTML is:

<div data-highlight="">
</div>

But this can be tricky. See in that first CSS block above, we’re wanting to target all elements with the data-highlight attribute, buttttt, we actually only wanna do it if it has a value. If the value is blank, we want to just skip any special styling at all.

In a perfect world, we’d just remove the data-attribute from the HTML template when there is no value. But a lot of templating languages, on purpose, don’t allow logic in them that would help us put-or-not-put that attribute entirely.

Instead, we can solve it with CSS:

[data-highlight]:not([data-highlight=""]) {
  font-size: 125%; 
}

[data-highlight="product"] img {
  order: 1;
}