简体   繁体   English

如果最接近的元素包含字符串,则向该元素添加类

[英]Add class to element if closest element contains string

I have some fixed HTML and I need to set a class to the element newgroup based on the element with the class relatedheader . 我有一些固定的HTML,我需要一个类设置为元素newgroup基于与类的元素relatedheader As you can see in the HTML, the first element has a string - Accessories . 如您在HTML中所见,第一个元素具有字符串Accessories I want to give the three elements below that element with the class newgroup to have class based on that string. 我想给该元素下面的三个元素加上类newgroup以使该类基于该字符串。 Then I want the next set to have class from the next relatedheader element. 然后,我希望下一个集合具有下一个relatedheader元素中的类。

How do I do this with jQuery or vanilla JS? 我该如何使用jQuery或Vanilla JS? I guess the first step is to make the relatedheader element a parent? 我想第一步是使relatedheader元素成为父元素?

What I got so far: 我到目前为止所得到的:

$('.relatedheader').nextUntil('.relatedheader').addClass('selected');

How do I make the script take the class dynamically releatedheader element? 如何使脚本采用类动态releatedheader元素?

<div class="relatedheader">
    <span class="unfoldedlabel" colspan="6">
        <a>Accessories/</a>
    </span>
</div>
<div class="newgroup"></div>
<div class="newgroup"></div>
<div class="newgroup"></div>
<div class="relatedheader">
    <span class="unfoldedlabel" colspan="6">
        <a>computers/</a>
    </span>
</div>
<div class="newgroup"></div>
<div class="newgroup"></div>
<div class="newgroup"></div>

Here you go: 干得好:

$(document).ready(function(){   

    $(".unfoldedlabel a").each(function(){

        if($(this).text() != "")
        {
            $(this).closest(".relatedheader").nextUntil(".relatedheader").addClass($(this).text().replace("/",""));
        }
    });
});

LINK To JSFIDDLE 链接到JSFIDDLE

Here is the working fiddle . 这是工作中的小提琴

$('.relatedheader').find('a').each(function() {
   $(this).parents('.relatedheader').nextUntil('div.relatedheader').addClass('selected');
});

Here in the above example I'm looping through each a inside .relatedheader class and then adding selected class to all element until next .relatedheader . 在这里,在上面的例子中我循环通过每个a内部.relatedheader类,然后添加selected类的所有元件,直到下一个.relatedheader

NOTE: If you want to only add those class to next set of element as per .relatedheader a selection or some event then you can bind this functionality to that event only. 注意:如果你想只有那些类添加到下一组元素按照.relatedheader a选择或某些事件,那么你可以绑定此功能仅该事件。

Hope this is what you need! 希望这就是您所需要的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM