I have the class button_cta in multiple places and would like to target it inside a div called mid-parent which is inside a div called big-parent and add the class not_united on it.
Using the code below the class is added but inside a sibling div to mid-parent inside there is a button_cta as well and it adds the class there too.
How do I target it only inside the mid-parent which is inside the big-parent?
I can't just target the mid-parent as that class is also used on other places and I need it to be targeted only when it's inside big-parent
$('.mid-parent').closest('.big-parent').find('.button_cta').addClass('not_united');
CodePudding user response:
Judging by the description, the simplest approach would be suitable here. Either my English is not so good. It would be cool if html markup was provided.
$('.big-parent .mid-parent .button_cta').addClass('not_united');
CodePudding user response:
Have you looked making your target more specific. I will recommend usng something along the line of:
$('div.mid-parent').closest('div.big-parent').find('.button_cta').addClass('not_united');
If 'button_cta' is a button you can even state that as well:
$('.mid-parent').closest('.big-parent').find('button.button_cta').addClass('not_united');
This way you make your target more specific
You can also use the parent and siblings methods in jQuery. For example:
$(this).parent('.parent').siblings('.siblings').children('.children').addClass("myClass");
jQuery allows you assign parent and siblings to classes, creating a hierarchical order.
