【问题标题】:Select element without style in jQuery在jQuery中选择没有样式的元素
【发布时间】:2014-01-14 22:55:21
【问题描述】:

通过类名选择元素很容易。但是,是否可以选择任何在 jQuery 中根本没有设置类的 DOM 元素?一种空样式选择器。

例子:

<div class="nope">
     <div>You need me!</div>
</div>
<span class="foo">Not me</span>

var answer = $("selector-im-looking-for").text(); // You need me!

【问题讨论】:

    标签: jquery


    【解决方案1】:

    我建议:

    $('div').not('[class]');
    

    JS Fiddle demo,请注意这种方法无法选择&lt;span&gt; 元素(下面的相关HTML)。

    或者,选择所有没有类属性的元素:

    $('body *:not("[class]")')
    

    JS Fiddle demo,注意这个未能选择&lt;span&gt;元素。

    通用选择器 (*) 隐含在伪类选择器不带标签名的情况下,但如果使用它,我更愿意明确说明它,尽管它是可选的上下文。

    进一步,选择 所有 元素,在 &lt;body&gt; 内,没有class 属性, 有一个类属性,但没有设置类名:

    $('body *').filter(function(){
        return !this.className || !this.className.length;
    })
    

    JS Fiddle demo,这种方法,因为它测试className 属性的缺失以及空/零长度className 属性,所以成功找到&lt;span&gt;

    以上demo都使用了以下HTML:

    <div class="nope">
        Some text that should not be selected.
         <div>You need me!</div>
    </div>
    <span class="foo">Not me</span>
    <span class="">Me too (probably)</span>
    

    参考资料:

    【讨论】:

    • Tnx!这是我正在寻找的选择器。我会在大约 9 分钟后接受它作为答案...
    【解决方案2】:

    您期待以下内容吗?

    var answer = $("div").text(); // You need me!
    

    或者

    var answer = $(":not(.nope)").text(); // You need me!
    

    编辑以下说明:

    像这样?

    var answer = $('div:not([class])');
    

    【讨论】:

    • Tnx 为您解答。但我正在寻找一个选择器,它可以选择任何没有类集的元素。
    • Tnx,最后一个是对的,但我只能接受一个。但是,tnx 无论如何!
    【解决方案3】:

    【讨论】:

    • Tnx 为您提供正确答案,但我接受了 David Thomas 的答案。
    【解决方案4】:

    你可以使用过滤器,

    $('div').filter(function(){
        return $(this).attr('class') === null;
    }).each(function(){
        //iterate item
    })
    

    【讨论】:

    • 我希望我没有冒犯您,但我选择格式化您的答案(为了将代码作为代码呈现,并且为了便于阅读)。如需格式化帮助(帮助您将代码格式化为代码),请查看Markdown help page。 :)
    猜你喜欢
    • 2011-01-04
    • 2020-05-21
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2013-07-17
    • 2010-10-24
    • 2013-05-01
    • 1970-01-01
    相关资源
    最近更新 更多