How to select HTML elements that do not have any attributes defined on them?

I need to use jQuery to search for all DIV tags that have no attributes, and apply a class to each. Here is an example HTML:

<div id="sidebar"> <div>Some text goes here</div> <div class="something">something goes here</div> <div>Another div with no attributes.</div> </div> 

So, I need to take this and turn it into:

 <div id="sidebar"> <div class="myClass">Some text goes here</div> <div class="something">something goes here</div> <div class="myClass">Another div with no attributes.</div> </div> 

How do you find div elements that have no attributes through jQuery? Thanks.

+4
source share
8 answers

Here you go:

 $('div', '#sidebar').filter(function () { return this.attributes.length === 0; }) 

Live demo: http://jsfiddle.net/phbU9/

The attributes property returns a list of all attributes set in the element. Bare items have an empty list of attributes .

Update: Be sure to read Tim's answer below, which offers a solution for older versions of IE, since my own solution does not work in IE8 and below.

+16
source

@ Šime's answer is close, but it doesn’t work in IE 6, 7 or 8, where the attributes element has an entry for every possible attribute, not just those specified in HTML. You can get around this by checking each property of the specified attribute object.

Live demo: http://jsfiddle.net/timdown/6MqmK/1/

code:

 $("div").filter(function() { var attrs = this.attributes, attrCount = attrs.length; if (attrCount == 0) { return true; } else { for (var i = 0; i < attrCount; ++i) { if (attrs[i].specified) { return false; } } return true; } }); 
+2
source

You need to give some kind of selector, in this case I used your sidebar, but it could be anything. Then get children who don't have a class attribute, and add a new class. See JSFiddle for an example:

http://jsfiddle.net/HenryGarle/q3x5W/

  $("#sidebar").children('div:not([class])').addClass('newClass'); 

This way, it will return 2 elements without a class tag and leave the sidebar and div with the class completely unaffected.

0
source

You can use a jQuery combination to have an attribute selector and not a selector . For instance:

 $('div:not([class], [id])').addClass('myClass'); 

jsFiddle demonstrating this

With this approach, you need to explicitly specify the attributes to check for availability. A Sime solution would apply the class to divs that have no attributes at all.

0
source

To explain Tim Down's answer, I recommend checking that the attrs var attribute is not null, where html has comment tags, etc.

0
source

try $ ('div: not ([class])'). addClass ('myClass'); this is a general approach because the class will be applied to all divs that don't have a class

-1
source
 $('#sidebar div')` or more general `$('div'); //returns collections of divs 

to answer the question:

 $('#sidebar div').addClass('myClass'); 
-6
source

All Articles