繁体   English   中英

如何 select HTML 元素上没有定义任何属性?

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

我需要使用 jQuery 来定位所有没有属性的 DIV 标签,并对每个标签应用 class。 这是一个示例 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>

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

<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>

如何通过 jQuery 定位没有属性的div类型元素? 谢谢。

这里是 go:

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

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

attributes属性返回在元素上设置的所有属性的列表。 “裸”元素有一个空attributes列表。

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

@Šime 的答案很接近,但在 IE 6、7 或 8 中不起作用,其中元素的attributes集合具有每个可能属性的条目,而不仅仅是 HTML 中指定的那些。 您可以通过检查每个属性对象的specified属性来解决这个问题。

现场演示: http://jsfiddle.net/timdown/6MqmK/1/

代码:

$("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;
    }
});

为了解释 Tim Down 的回答,我建议检查 attrs var 不是 null 特殊情况,其中 html 有评论标签等。

您需要提供某种选择器,在这种情况下,我使用了您的侧栏,但它可以是任何东西。 然后获取没有 class 属性的孩子,并添加一个新的 class。 有关示例,请参见 JSFiddle:

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

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

因此,这将返回没有 class 标记的 2 个元素,并使 class 的侧边栏和 div 完全不受影响。

您可以使用 jQuery 的has 属性选择器not 选择器的组合。 例如:

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

jsFiddle 演示了这一点

使用这种方法,您需要显式指定要检查存在的属性。 Sime 的解决方案会将 class 应用于根本没有任何属性的 div。

试试 $('div:not([class])').addClass('myClass'); 这是一种通用方法,因为 class 将适用于所有没有 class 的 div

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

回答这个问题:

$('#sidebar div').addClass('myClass');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM