I need to use jQuery to locate all DIV tags that have no attributes on them and apply a class to each. Here’s a sample 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 that and turn it into this:
<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 locate elements of type div that have no attributes via jQuery? Thanks.
Here you go:
Live demo: http://jsfiddle.net/phbU9/
The
attributesproperty returns a list of all attributes set on the element. “Naked” elements have an emptyattributeslist.Update: Be sure to read Tim’s answer below which provides a solution for older versions of IE, since my own solution doesn’t work in IE8 and below.