jQuery get all divs which do not have class attribute

get all divs which has class attribute

$('div[class]')

get all divs which do not have class attribute

$('div[class!=""]')

This code works but I don't understand why it works. If the above code works then the code for all divs with class attribute should be

$('div[class=""]') 

which does not yield any result.


Try it with the :not() pseudo-class selector:

$('div:not([class])')

Edit

The description for the jQuery selectors say:

  • [attribute]
    Matches elements that have the specified attribute.
  • [attribute=value]
    Matches elements that have the specified attribute with a certain value.
  • [attribute!=value]
    Matches elements that either don't have the specified attribute or do have the specified attribute but not with a certain value.

This means div[class=""] would select all DIV elements that have a class attribute specified with an empty value.

But the last selector is a proprietary selector of jQuery and not a CSS selector. You would need to use :not() to select all DIV elements that do not have a class:

div:not([class])

What is important to realize is that there are empty class attributes as well as elements without a class attribute, but they require different tests to select.

There are a number of tests that all do different things. Here is our HTML for our tests:

<div class="">Empty Class Attribute </div>
<div class="column">Full Class Attribute </div>
<div>No Class Attribute </div>

Now, lets run our tests (The first part is simply a string that helps us know what was just called in the alert, otherwise it is meaningless):

$(document).ready(function(e){
  // Outputs "Empty Class Attribute Full Class Attribute"
  alert( "div[class] : "     + $('div[class]').text()     );

  // Outputs "Full Class Attribute"
  alert( "div[class!=''] : " + $('div[class!=""]').text() );

  // Outputs "Empty Class Attribute" 
  alert( "div[class=''] : "  + $('div[class=""]').text()  );

  // Outputs "No class Attribute"
  alert( "div:not([class]) : " + $('div:not([class])').text()     );
});

You can view this code in your browser by visiting here: http://jsbin.com/ijupu

Now, armed with this knowledge, if you wanted to select every div element on the page with either a blank attribute and no attribute, use the following selector:

$("div[class=''], div:not([class])");

The $('div[class=""]') selector essentially reads: "Get all div elements whose class attribute has an empty string as its value." - That excludes all div elements that have ANY value in the class attribute, other than an empty string, and all div elements that do not have the class attribute set at all.