Empty and non empty attribute selectors in CSS
This note is about empty and non empty attribute CSS selectors.
To select some elements in CSS by attribute value we should use attribute selectors. There’s an attribute selector that matches elements when their attribute exactly equals to a specified value in the selector.
1 2 3 |
[attribute='value'] { } |
So, to select elements with an empty attribute we should use the following CSS:
1 2 3 |
div[data-attr=''] { } |
Unfortunately, there isn’t “not empty” attribute selector but we can get the same effect using :not()
selector: Here’s an example:
1 2 3 |
:not([data-attr='']) { } |
You can try it here http://codepen.io/starikovs/pen/tngqH.
Always nice to read useful tidbits like this on the web. However, for most cases you would probably want the selector to match where the attribute exists but is not empty. The code you have here matches if it doesn’t exist or is not empty.
To match where the attribute exists but is not empty, you need to combine the attribute exists selector with the selector you have:
:not([data-attr=''])[data-attr] {
}
Andy Earnshaw, thanks for this remark
Can’t you just use: div[attribute]
Mike Plant,
div[attribute] selects elements with the specified attribute, but it may be empty of not. What if you want to know exactly that attribute is empty or not?