jQuery 选择没有任何类的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4991576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:20:24  来源:igfitidea点击:

Select elements without any class

jqueryhtmljquery-selectors

提问by PadovaBoy

I need to find, via jQuery selectors, all spans in a page that have no class.

我需要通过 jQuery 选择器找到没有类的页面中的所有跨度。

Example:

例子:

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

回答by BoltClock

Use :not()and the attribute not selector [att!=val]to filter out elements with a non-empty classattribute:

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

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

jsFiddle preview

jsFiddle 预览

Note however that [att!=val]is a non-standard jQuery selector, which means the selector cannot be used in CSS or with document.querySelectorAll(). If you're like me, and you're a stickler for following the standards and so want to eschew non-standard jQuery selectors where possible, the following is a direct equivalent:

但是请注意,这[att!=val]是一个非标准的 jQuery 选择器,这意味着该选择器不能在 CSS 中使用或与document.querySelectorAll(). 如果您和我一样,并且是遵循标准的坚持者,因此希望尽可能避免使用非标准的 jQuery 选择器,那么以下是直接等效的:

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

This matches

这匹配

  • spanelements that have noclassattribute, and
  • spanelements that dohave a classattribute, but only when the attribute value is empty.
  • span没有class属性的元素,以及
  • span该元素有一个class属性,但只有当属性值是空的。

In most cases, though, you should be able to get away with just the first portion:

但是,在大多数情况下,您应该能够只使用第一部分:

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

You'll usually only find empty classattributes in markup generated by the application that's responsible for outputting it, or by developers who aren't paying attention.

您通常只会class在由负责输出它的应用程序或不注意的开发人员生成的标记中找到空属性。

回答by Milche Patern

See this answer to do it with css only Can I write a CSS selector selecting elements NOT having a certain class?

请参阅此答案以仅使用 css我可以编写一个 CSS 选择器来选择没有特定类的元素吗?

:not([class])

Actually, this will select anything witch do not have a .class applied to it.

实际上,这将选择任何没有应用 .class 的女巫。

I gathered a jsfiddledemo

我收集了一个jsfiddle演示

html

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

css

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