Targeting Selectors Without a Class Attribute Bookmark

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 ;)


Leave a comment

Available formatting commands

Use Markdown commands or their HTML equivalents to add simple formatting to your comment:

Text markup
*italic*, **bold**, ~~strikethrough~~, `code` and <mark>marked text</mark>.
Lists
- Unordered item 1
- Unordered list item 2
1. Ordered list item 1
2. Ordered list item 2
Quotations
> Quoted text
Code blocks
```
// A simple code block
```
```php
// Some PHP code
phpinfo();
```
Links
[Link text](https://example.com)
Full URLs are automatically converted into links.

Replied on your own website? Send a Webmention!