admin管理员组文章数量:1406178
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="" class="ifthis"> <b>This Text Should Red</b></a>
</li>
<li><a href="" 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.
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./slycolor" class="ifthis"> <b>This Text Should Red</b></a>
</li>
<li><a href="https://www.facebook./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.
Share Improve this question asked Aug 25, 2015 at 17:44 AaribaAariba 1,1945 gold badges23 silver badges54 bronze badges2 Answers
Reset to default 5Select 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,
has()
will only check that it's descendant has contain that selector, you needfilter()
instead.parent()
will only select immediate parent , so you should useparents()
orclosest()
.
With your code :
$('.widget-content li a').filter('.ifthis').parents('.widget-content').addClass('social-sidebar');
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./closest/
https://api.jquery./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.
本文标签: javascriptAdd class to parent div if there has specific classStack Overflow
版权声明:本文标题:javascript - Add class to parent div if there has specific class - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744971080a2635238.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论