如何选择没有定义任何属性的HTML元素?

Ale*_*lex 4 html javascript jquery

我需要使用jQuery来查找所有没有属性的DIV标记,并为每个标记应用一个类.这是一个示例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>
Run Code Online (Sandbox Code Playgroud)

所以,我需要把它变成这个:

<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>
Run Code Online (Sandbox Code Playgroud)

如何div通过jQuery 找到没有属性的类型元素?谢谢.

Šim*_*das 16

干得好:

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

现场演示: http ://jsfiddle.net/phbU9/

attributes属性返回元素上设置的所有属性的列表."Naked"元素有一个空attributes列表.

更新:请务必阅读下面的Tim的答案,该答案为旧版本的IE提供了解决方案,因为我自己的解决方案在IE8及更低版本中不起作用.