Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 688
Roger Avatar asked Dec 25 '09 23:12

Roger


2 Answers

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]) 
like image 166
Gumbo Avatar answered Oct 08 '22 15:10

Gumbo


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])"); 
like image 44
Doug Neiner Avatar answered Oct 08 '22 13:10

Doug Neiner