Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select HTML elements which don't have any attributes defined on them?

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.

like image 350
Alex Avatar asked Dec 22 '22 10:12

Alex


2 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 on the element. "Naked" elements have an empty attributes list.

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.

like image 97
Šime Vidas Avatar answered Dec 24 '22 00:12

Šime Vidas


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

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;
    }
});
like image 37
Tim Down Avatar answered Dec 24 '22 00:12

Tim Down