2011-02-14 124 views
37

我需要通过jQuery选择器查找页面中没有类的所有跨度。选择没有任何类的元素

实施例:

<span class='Cool'>do not found me</span> 
<span>me, me, take me please!!!</span> 

回答

59

使用:not()attribute not selector [att!=val]过滤掉具有非空class属性元素:然而

$('span:not([class!=""])') 

jsFiddle preview

注意[att!=val]是非易失标准的jQuery选择器,这意味着选择器不能用于CSS或with document.querySelectorAll()。如果你像我,你是个坚持己见继该标准,因此希望在可能避开非标准jQuery选择,下面是一个直接等同:

$('span:not([class]), span[class=""]') 

这符合

  • span元素有没有class属性,
  • span元素class属性,但只有当属性值为空。

在大多数情况下,但是,你应该能够逃脱仅仅是第一部分:

$('span:not([class])') 

你通常只能找到这就是负责应用程序生成的标记空class属性输出它,或者不注意的开发者。

+0

Bolclock嗨!不适合我!但相反,这工作得很好:跨度:不(([班级]) 谢谢你的建议!我做到了;) – PadovaBoy 2011-02-14 11:35:11

+0

@PadovaBoy:我的代码如何不适合你? `[!=“”]`自从jQuery的第一个版本开始出现。 – BoltClock 2011-02-14 11:35:53

4

看到这个答案与CSS做只是Can I write a CSS selector selecting elements NOT having a certain class?

:not([class]) 

事实上,这将选择什么女巫没有应用到它的.class。

我聚集了jsfiddle演示

HTML

<h2 class="fake-class">fake-class will be green</h2> 
<h2 class="">empty class SHOULD be white</h2> 
<h2>no class should be red</h2> 
<h2 class="fake-clas2s">fake-class2 SHOULD be white</h2> 
<h2 class="">empty class2 SHOULD be white</h2> 
<h2>no class2 SHOULD be red</h2> 

CSS

h2 {color:#fff} 
:not([class]) {color:red;background-color:blue} 
.fake-class {color:green} 
相关问题