当元素具有多个类时,jquery 按特定类查找元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7587966/
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-27 00:02:00  来源:igfitidea点击:

jquery find element by specific class when element has multiple classes

jqueryclasselements

提问by chris

So I am working on something that wasn't well thought out in the build from the backend team. That leaves me with a document full of divs.

所以我正在研究后端团队在构建中没有经过深思熟虑的事情。这给我留下了一个充满 div 的文档。

What I am doing is rolling back from the element I need to click on, get the parent container then find an element within the parent which has class="alert-box warn", class="alert-box dead", etc... Essentially, I'm trying to use multiple class selectors on each element. When I try to find just alert-boxit doesn't seem to be working right. I'm assuming because it has warn,dead, ``fine, etc...

什么我做的是从滚动元件回我需要点击,然后拿到父容器找到它具有父中的元素class="alert-box warn"class="alert-box dead"等等......从本质上讲,我想每一个元素上使用多个类选择。当我试图找到alert-box它时,它似乎无法正常工作。我假设因为它已经warn,死了,``很好,等等......

How can I find just alert-box*or equivalent to a wildcard concept?

我如何才能找到alert-box*与通配符概念相同或等效的概念?

回答by John Hartsock

You can combine selectors like this

您可以像这样组合选择器

$(".alert-box.warn, .alert-box.dead");

Or if you want a wildcard use the attribute-contains selector

或者,如果您想要通配符,请使用属性包含选择器

$("[class*='alert-box']");

Note: Preferably you would know the element type or tag when using the selectors above. Knowing the tag can make the selector more efficient.

注意:最好在使用上面的选择器时知道元素类型或标签。知道标签可以使选择器更有效率。

$("div.alert-box.warn, div.alert-box.dead");
$("div[class*='alert-box']");

回答by Bojangles

You can select elements with multiple classes like so:

您可以选择具有多个类的元素,如下所示:

$("element.firstClass.anotherClass");

Simply chain the next class onto the first one, withouta space (spaces mean "children of").

只需将下一个类链接到第一个类上,无需空格(空格表示“的孩子”)。

回答by Igor Dymov

var divs = $("div[class*='alert-box']");

回答by Kevin B

An element can have any number of classNames, however, it can only have one class attribute; only the first one will be read by jQuery.

一个元素可以有任意数量的 classNames,但是它只能有一个 class 属性;jQuery 只会读取第一个。

Using the code you posted, $(".alert-box.warn")will work but $(".alert-box.dead")will not.

使用您发布的代码,$(".alert-box.warn")将工作,但$(".alert-box.dead")不会。

回答by isJustMe

you are looking for http://api.jquery.com/hasClass/

你正在寻找 http://api.jquery.com/hasClass/

<div id="mydiv" class="foo bar"></div>

$('#mydiv').hasClass('foo') //returns ture