如何检查元素的内容是否为空,如果是,在jquery中删除该元素 [英] How to check if content of element is empty and if so, remove that element in jquery

查看:214
本文介绍了如何检查元素的内容是否为空,如果是,在jquery中删除该元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试选择某个div中没有​​内容的任何h2元素,并删除它。这是我的html代码:

 < div class =skipToContainer> 
< h2 class =vidSkipTo> Hello< / h2>
< h2 class =vidSkipTo>< / h2>
< h2 class =vidSkipTo>< / h2>
< h2 class =vidSkipTo>< / h2>
< / div>

这些是一对jQuery代码我试图无效:

  jQuery(skipToContainer .vidSkipTo)每个(function(){
if(jQuery ==='')
jQuery(this).remove();
}

jQuery(skipToContainer h2 b if(jQuery(this).text()。trim()==='')
jQuery(this).remove();
}

jQuery .skipToContainer h2)。each(function(){
if(jQuery(this).text()==='')
jQuery(this).remove();
}

有任何建议吗?




解决方案 注意:我在本地WordPress网站上进行这些测试,不知道是否重要, div>

尝试



  jQuery(。skipToContainer h2)filter(:empty code> 

 < script src =https://ajax.googleapis。 com / ajax / libs / jquery / 1.11.1 / jquery.min.js>< / script> < div class =skipToContainer> < h2 class =vidSkipTo> Hello< / h2> < h2 class =vidSkipTo>< / h2> < h2 class =vidSkipTo>< / h2> < h2 class =vidSkipTo>< / h2> < / div>  


I'm currently trying to select any h2 element inside of a certain div that does not have content in it and remove it. This is my html code:

 <div class="skipToContainer">
     <h2 class="vidSkipTo">Hello </h2>
     <h2 class="vidSkipTo"></h2>
     <h2 class="vidSkipTo"></h2>
     <h2 class="vidSkipTo"></h2>
 </div>

These are a couple jQuery codes I have tried to no avail:

jQuery(".skipToContainer .vidSkipTo").each (function () {
    if (jQuery(this).text().trim() === '')
        jQuery(this).remove();
}

jQuery(".skipToContainer h2").each (function () {
    if (jQuery(this).text().trim() === '')
        jQuery(this).remove();
}

jQuery(".skipToContainer h2").each (function () {
    if (jQuery(this).text() === '')
        jQuery(this).remove();
}

Any suggestions?

Note: I'm doing these tests on a local WordPress site. Not sure if that matters but just to let you know.

解决方案

Try

jQuery(".skipToContainer h2").filter(":empty").remove();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
 <div class="skipToContainer">

          <h2 class="vidSkipTo">Hello </h2>
          <h2 class="vidSkipTo"></h2>
          <h2 class="vidSkipTo"></h2>
          <h2 class="vidSkipTo"></h2>

 </div>

这篇关于如何检查元素的内容是否为空,如果是,在jquery中删除该元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆