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][attribute=value][attribute!=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])");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With