[英]Add class to parent div if there has specific class
Trying to add class to parent div <div class="widget-content">
if .widget-content li a
has specific class .ifthis
. 如果
.widget-content li a
具有特定的类.ifthis
尝试将类添加到父div <div class="widget-content">
。
HTML: 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 . 但没有工作,看到这个例子小提琴 。
Select children which have class ifthis
then select it's parent using parents()
or closest()
选择具有
ifthis
孩子,然后使用parents()
或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 need filter()
instead. has()
将仅检查其后代是否包含该选择器,而需要使用filter()
。 parent()
will only select immediate parent , so you should use parents()
or closest()
. parent()
将仅选择直接父级,因此您应使用parents()
或closest()
。 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.com/closest/ 参考: https : //api.jquery.com/closest/
https://api.jquery.com/has-selector/ https://api.jquery.com/has-selector/
.closest( selector ) -- Returns: jQuery
.closest(选择器)-返回: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.
说明:对于集合中的每个元素,通过测试元素本身并遍历DOM树中的其祖先,获得与选择器匹配的第一个元素。
:has() Selector :has()选择器
jQuery( ":has(selector)" ) -- Returns: jQuery
jQuery(“:has(selector)”)-返回:jQuery
Description: Selects elements which contain at least one element that matches the specified selector.
说明:选择包含至少一个与指定选择器匹配的元素的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.