Targeting Selectors Without a Class Attribute
published on
I recently ran into the issue that I needed to target certain <li>
elements whose parent <ul>
does not contain a class attribute. I might have been able to solve this issue in a different way, but in this case the parent <ul>
s won't ever—never say never! ;)—have a class attribute, this method works well. It wasn’t the cleanest possible solution, but sometimes things need to give.
Most of the time I usually target elements or class names, but the following selector can definitely be helpful once in a while.
By using the :not()
CSS pseudo-class (also known as the negation pseudo-class), it’s possible to exclude certain values from the selection. In this case I wanted to check for the presence of a class
attribute, rather than its value. To do that, we can make use of the CSS attribute selector.
Combined, these two can make a powerful pair.
ul:not([class]) li {
property: value;
}
The above CSS rule targets the <li>
of this list:
<ul>
<li>Text</li>
</ul
But not of this:
<ul class="">
<li>Text</li>
</ul
or this:
<ul class="classname">
<li>Text</li>
</ul
I hope you found this article useful and will enjoy excluding elements from now on ;)