Nicholas Pappas
Nicholas Pappas

Reputation: 10624

Determining if an attribute is absent via CSS Attribute Selector?

Can the CSS Attribute Selector, and/or combination of selectors, be used to determine if an attribute is absent?

An attribute selector can be used to test if the attribute is blank:

[aria-label='']

... but the attribute still must be present in order for that to pass. If the HTML tag does not have the attribute at all, the above selector does not pass.

Can a selector be written in a way that it would pass if the attribute is not there?

Upvotes: 3

Views: 764

Answers (3)

Michael Benjamin
Michael Benjamin

Reputation: 372079

You can apply a combination of the attribute selector and :not() negation pseudo-class:

div[orange] { background-color: orange; }                       /* 1 */

div:not([orange]) { background-color: lightgreen; }             /* 2 */

div { height: 50px; }
<div>Does not have the orange attribute</div>
<div orange>Has the orange attribute</div>
<div green>Does not have the orange attribute</div>
<div orange="orange">Has the orange attribute</div>

Notes:

  1. Target divs with orange attribute.
  2. Target divs that do not have the orange attribute.

References:

Upvotes: 2

Amit
Amit

Reputation: 46361

Yes, and it's quite simple with the :not() pseudo-class:

span:not([wrong]) {
  color: blue
}
<span>I have no attribute</span><br/>
<span wrong>I have the wrong attribute :-(</span>

Upvotes: 2

Cameron
Cameron

Reputation: 694

Something like this?

div:not([aria-label]) {
  color: red;  
}
<div aria-label="test">
  test
</div>

<div>
  test2
</div>

Upvotes: 1

Related Questions