Jquery 如果子级有内容,则将类添加到父级
如果类为.present的子元素有任何html内容,我将尝试向最近的元素添加一个类 我现在的代码Jquery 如果子级有内容,则将类添加到父级,jquery,Jquery,如果类为.present的子元素有任何html内容,我将尝试向最近的元素添加一个类 我现在的代码 <article> <div class="box"> <h2>1 dec</h2> </div> <div class="present"> <h1>HAS CONTENT</h1> </div> </article> <script&g
<article>
<div class="box">
<h2>1 dec</h2>
</div>
<div class="present">
<h1>HAS CONTENT</h1>
</div>
</article>
<script>
$(document).ready(function(){
if ($(".present").html().length > 0) {
$(this).parent().addClass('active');
}
});
</script>
12月1日
有内容
$(文档).ready(函数(){
如果($(“.present”).html().length>0){
$(this.parent().addClass('active');
}
});
我已经测试了console.log so的条件是否作为true返回,但活动类没有添加到父元素中。有人能告诉我我做错了什么吗?您可以使用获取没有html的元素,然后让它们的父级添加类
编辑
要将类添加到.present
中,可以跳过.parent()
您在
$(“.present”)
上测试条件,然后要求$(this).parent()
而不是$('.present')。parent()
为什么不$(.present”).children().length>0
?@MatteoTassinari这将为每篇文章添加活动类,我只需要将类添加到.present中包含内容的类element@reporter这对将类添加到.present元素的父项目有何帮助,我不理解你的问题。这可以用来检查元素是否有内容吗?在添加活动类return$(this).html().trim().length>0之前,最好先修剪空白代码>@Danield-你解决了!没有考虑到空白,它被视为实际内容,谢谢接受@Danield编辑的答案,谢谢大家
$(".present").filter(function(){
return $(this).html().trim().length > 0;
}).parent().addClass('active');
$(".present").filter(function(){
return $(this).html().trim().length > 0;
}).addClass('active');