How to select HTML element without attribute with CSS?
There might be cases, where You want to select element that does not have particular attribute. Not have attribute might actually mean two different aspects. One could consider empty attribute like if it not exists, while other would said that the element have attribute but empty. We will focus here on case where we treat both empty or non existent attribute as non existent.
The use case here is to select all bare links, in other words
those links that do not have any CSS class applied. To
select those elements, we need to use attribute selector twice,
once assuming empty content and the other one assuming no
attribute at all. To select elements without attribute we can use
not
selector extension while for empty
attribute attribute just CSS attribute selector with empty
value.
Example
Selecting all a
elements that do not have CSS class
applied:
a:not([class]), a[class=""]{ color: blue; }
The first selector selects all a
elements that do
not have class attribute, the latter one selects all with empty
class attribute. The same technique can be used to select any
other elements with empty attribute.
The selector will match for example:
<a href="//maslosoft.com"></a>
<a href="//maslosoft.com" class=""></a>
But will not match:
<a href="//maslosoft.com" class="btn btn-success"></a>
Selecting Elements That Don't Have Particular Attribute or Have It Empty
As in class example we need to combine not
attribute
selector with empty attribute selector:
div:not([id]), div[id=""]{ background-color: red; }
This will match any div
element without (or
empty) id
attribute:
<div class="alert alert-success"></div> <div id=""></div>
But will not match if element have any value on
id
attribute:
<div id="alert" class="alert alert-success"></div> <div id="content"></div>
Selecting Elements That Don't Have Particular Attribute
not
operator.
For example let's use data-name
custom attribute
selector:
not
operator, let's
use it on form
elements:
form:not([data-name]){ color: blue; }
This will match elements that do not have
data-name
attribute:
<form data-name="login"></form>
But it will not match those which have
empty data-name
attribute:
<form data-name=""></form> <form data-name></form>