简体   繁体   中英

How do I add class or id in this element just knowing that there is more than one element containing " .sided-sections .widget "

var b = ('data-type');

if ($(b + ":contains('cover')")) {
  $(".sided-sections .widget").addClass("cate-cover")
}

i want repair this code please because when I add this code it adds a class to all elements that contain " .sided-sections .widget " so I want to dedicate something to that where the class adds on data-type='cover' only and thank you

A jQuery selector doesn't return a true/false value that can be used in .match() . If you want to know if a selector finds anything, you need to get its length.

Furthermore, if doesn't set this to the elements that the selector matches. If you want to set this , you need to use .each() to loop over all the matching elements.

$(b + ":contains('cover')").each(function() {
    $(this).siblings(".sided-sections .widget").addClass("cate-cover");
});

But you don't even need that, because you can apply .siblings() directly to the selector:

$(b + ":contains('cover')").siblings(".sided-sections .widget").addClass("cate-cover");

If this doesn't work, add the HTML to your question, and point out which elements should get the cate-cover class. You might have the relationships between the selectors wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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