jQuery - 如果所有 Child 元素都具有相同的 class 添加额外的 class 到页面上的另一个元素

jQuery - If all Child elements have same class add additional class to another element on the page

我希望能够使用 jQuery 检查所有 child 元素是否共享相同的 class。如果所有 child 元素都具有相同的 class,那么我想将额外的 class 应用到页面上不是直接 child 而是最接近的 h4 的另一个元素。

有问题的 HTML 元素在附图中。该代码由插件自动生成。

目前我正在寻找任何包含 0 的元素,并且 class 没有应用任何项目。这可以在屏幕截图中看到。

图像顶部的 h4 是需要 class 添加的元素,如果所有 children 都具有 "no-items" 的 class

基本HTML示例

<div>
<h4>This is the element that needs a class if all li's have the class of no-items</h4>
<ul>
    <li class="no-items">0</li>
    <li class="no-items">0</li>
    <li class="">1</li>
    <li class="no-items">0</li>
</ul>

尝试了新代码,结果如截图所示。

enter image description here

$('.woof_container_inner h4').addClass(function(){
if( $(this).next('ul').find('li').length === $(this).next('ul').find('li.noitems').length ) return 'someclass';

})

"someclass" 仅应应用于 H4 元素,前提是 ul 中的所有 li 都没有 class 项。如果没有什么也不做。

这样做就可以了:

$('h4').addClass(function(){
    if( $(this).next('ul').find('li').length === $(this).next('ul').find('li.no-items').length ) return 'someclass';
})

这将应用于页面上的所有 h4 元素,因此您可能需要使其更具体。

它的作用是寻找一个 h4 元素并添加一个 class 如果它后面的列表中的列表项数等于没有项的列表项数 class .

使用来自 @j08691 的代码进行一些小的修改很高兴地说以下代码对我有用。

$('.woof_container_inner h4').addClass(function(){
if( $(this).next('div').find('li').length === $(this).next('div').find('li.noitems').length ) return 'no-heading';

})

我已将上面的代码与以下代码组合在一起,因此它会在每个 Ajax 过滤器被选中后执行。

$(文档).ajaxSuccess(函数(){

$('.woof_container_inner h4').addClass(函数(){ 如果( $(this).next('div').find('li').length === $(this).next('div').find('li.noitems' ).length ) return 'no-heading'; })

});