Select an Element with a Non-Empty Attribute

Select an Element with a Non-Empty Attribute

At 3/31/2024

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

We respect the property rights of others and are always careful not to infringe on their rights, so authors and publishing houses have the right to demand that an article or book download link be removed from the site. If you find an article or book of yours and do not agree to the posting of a download link, or you have a suggestion or complaint, write to us through the Contact Us, or by email at: support@freewsad.com.

More About us