简体   繁体   中英

If div inside other divs hasClass, addClass to top level div

I have a question. I currently have a bunch of divs inside my sidebar.

The structure is like this: div.toggle-container > div > div.showme > div.berocket_single_filter_widget

This divs are generated from a wordpress plugin to show product filters. Sometimes when a filter is empty the class below is added.

div.bapf_mt_none

So the structure then becomes:

div.toggle-container > div > div.showme > div.berocket_single_filter_widget.div.bapf_mt_none

Im trying to add a class with jQuery so that when if the class.div.bapf_mt_none exists inside these other divs. I want to add a class to div.toggle-container

But im stuck.

All help is appreciated.

Thanks

I'm trying to add a class when the class.div.bapf_mt_none exists inside these other divs. I want to add a class to div.toggle-container

You could go with a solution that takes the top .toggle-container , then looks inside the structure to find where .berocket_single_filter_widget has .bapf_mt_none , alternatively, you could look directly for .bapf_mt_none then navigate up to add the class to the container:

$(".bapf_mt_none").closest(".toggle-container").addClass(".empty");

(using .empty as an example)

If you find .bapf_mt_none occurs in places other than your filter, you can be more specific in the selector, eg:

$("div.toggle-container > div > div.showme > div.berocket_single_filter_widget.div.bapf_mt_none")
    .closest(".toggle-container")
    .addClass(".empty");

but the concept is the same - look for the bottom level and, thanks to the way jquery works, it will then apply to all matching parents for all elements found. If none found, .empty (in the example) won't be applied.

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