Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select elements with empty or not-specified attribute

Take the following, schematic html-code:

<div>
  <span id='1' cust-attr='' />
  <span id='2' />
  <span id='3' cust-attr='Foo' />
</div>

Now I am looking for a selector finding all spans which either do not have an attribute "cust-attr" or whose "cust-attr" value is empty.
In this case, this would be the 1 and 2.

I tried the following selectors with the following results:

  1. span[cust-attr!=] selects 2 and 3
  2. span[cust-attr=''] only selects 1
  3. span:not([cust-attr]) selects 2
  4. span(:not([cust-attr]),[cust-attr='']) selects all three
  5. span([cust-attr=''],:not([cust-attr])) selects 1

However, I did not find one selecting only 1 and 2.
Do you know a possibility?

Note that I want to avoid:

span:not([cust-attr]),span[cust-attr='']

as "span" is in reality a more complex expression.

like image 252
Matthias Avatar asked Apr 02 '11 15:04

Matthias


People also ask

Which selector selects elements with a specific class attribute?

The .class selector selects elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class.

How can we select elements with a specified attribute in CSS?

The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".

What is an empty attribute?

When an HTML tag contains an attribute with no value set (indicated by no information between the quotation marks) it is said to have an "empty" attribute.

Which selector selects elements based on an attribute or attribute value?

The CSS attribute selector matches elements based on the presence or value of a given attribute.


1 Answers

Late to the party...

... or you could use CSS Selectors and be 10x as fast as both jQuery answers... :)

document.querySelectorAll("input:not([id]), input[id='']");

Proof

like image 167
JeffC Avatar answered Sep 16 '22 17:09

JeffC