Add class to parent div if there has specific class

喜夏-厌秋 提交于 2019-11-30 21:04:19

问题


Trying to add class to parent div <div class="widget-content"> if .widget-content li a has specific class .ifthis.

HTML:

<div class="widget-content">
<ul>
<li><a href="https://twitter.com/slycolor" class="ifthis"> <b>This Text Should Red</b></a>
</li>

<li><a href="https://www.facebook.com/slycolor" class="ifthis"> <b>This Text Should Red</b></a>
</li>
</ul>
</div>

I have tried This:

$('.widget-content li a').has('.ifthis').parent('.widget-content').addClass('social-sidebar'); 

But not working, see this example fiddle.


回答1:


Select children which have class ifthis then select it's parent using parents() or closest()

$('.widget-content li a.ifthis').parents('.widget-content').addClass('social-sidebar'); 

OR

$('.widget-content li a.ifthis').closest('.widget-content').addClass('social-sidebar');

Your code is not working because,

  1. has() will only check that it's descendant has contain that selector, you need filter() instead.
  2. parent() will only select immediate parent , so you should use parents() or closest().

With your code :

$('.widget-content li a').filter('.ifthis').parents('.widget-content').addClass('social-sidebar'); 



回答2:


Use this:

$('a.ifthis').closest('div.widget-content').addClass('social-sidebar');

Or:

$('.ifthis').closest('.widget-content').addClass('social-sidebar');
//if only a elements have .ifthis and only div elements have .widget-content

Or:

$('.widget-content:has(.ifthis)').addClass('social-sidebar');

Ref: https://api.jquery.com/closest/
https://api.jquery.com/has-selector/

.closest( selector ) -- Returns: jQuery

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

:has() Selector

jQuery( ":has(selector)" ) -- Returns: jQuery

Description: Selects elements which contain at least one element that matches the specified selector.



来源:https://stackoverflow.com/questions/32210695/add-class-to-parent-div-if-there-has-specific-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!