jQuery addClass 到每个具有“.class”子元素的元素

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

jQuery addClass to each element that has children with '.class'

jqueryeachaddclass

提问by rzr

I'm trying to add a Class to each anchor inside #somecontainerwhose children have .someclass

我正在尝试为每个#somecontainer孩子的锚点添加一个类.someclass

For example.

例如。

<div id="container">
<a><span class="someclass"></span></a>
<a></a>
<a><span class="someclass">/span></a>
</div>

In the above code i want the first and third anchors to have a class '.anotherclass' I tried this code but it doesn't seem to work

在上面的代码中,我希望第一个和第三个锚点有一个类 '.anotherclass' 我试过这段代码,但它似乎不起作用

jQuery('#container a').each(function(){
jQuery(this).has('.someclass').addClass('anotherclass');
})

Update: .has()returns a booleanand not jQuery object. That's why the code didn't work

更新.has()返回一个boolean而不是 jQuery 对象。这就是代码不起作用的原因

回答by Asad Saeeduddin

I suspect your problem stems from the fact that your HTML is malformed, i.e. you need to close your spans.

我怀疑您的问题源于您的 HTML 格式错误,即您需要关闭跨度。

<div id="container">
<a><span class="someclass"></span></a>
<a></a>
<a><span class="someclass"></span></a>
</div>

Additionally, your code can be simplified a bit by using :hasto select only anchors that contain an element matching your desired class name:

此外,您的代码可以通过使用:has仅选择包含与您想要的类名匹配的元素的锚点来稍微简化:

$('#container a:has(.someclass)').addClass('anotherclass');

i.e. "select all anchors that are descendants of an element with ID containerand that have a descendant with class someclass"

即“选择所有具有 ID 的元素container的后代且具有类的后代的锚someclass

As Jon has pointed out, an alternative is to use a basic selector, then filter the resulting collection using a custom function:

正如 Jon 所指出的,另一种方法是使用基本选择器,然后使用自定义函数过滤结果集合:

$('#container a').filter(function(){
    return $(this).has('.someclass').length > 0
}).each(function(){
    $(this).addClass('anotherclass');
});

The function needs to return truefor any element that you want to retain, and falsefor any element you don't.

该函数需要为true您想要保留false的任何元素以及您不需要的任何元素返回。

回答by Chamila Chulatunga

Try:

尝试:

$('#container a .someclass').parents('a').addClass('anotherClass');

Basically we work our way right down to find the elements with the class 'someclass': $('#container a .someclass'), and then from there work our way back up to the enclosing anchor: .parents('a'), which is where the class 'anotherclass' needs to be added.

基本上,我们直接向下查找具有类 'someclass': 的元素$('#container a .someclass'),然后从那里返回到封闭的 anchor: .parents('a'),这是需要添加类 'anotherclass' 的地方。

回答by Paul Verbeek-Mast

jQuery('#container a .someclass').parent().addClass('anotherclass');?