检查DOM元素和子元素是否包含任何文本[JS或jQuery] [英] Check if DOM element and children contains any text [JS or jQuery]

查看:114
本文介绍了检查DOM元素和子元素是否包含任何文本[JS或jQuery]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够检查元素是否包含其中的任何文本。我希望能够删除元素,如果没有任何文本。

I want to be able to check if an element contains any text inside of it. I want to be able to remove the element if there isn't any text in it.

但是,这个dom元素可能包含一个或多个子元素,以及那些孩子也可能包含其他孩子。所以我希望能够跟随元素的dom树并搜索其中的所有元素以获取文本。

However, this dom element might contain a children, or more, and those children might contain other children as well. So I want to be able to follow the dom tree of the element and search through all of the elements inside it for text.

这样的事情:

<div id="myElement">
  <span></span>
  <span></span>
  <span>
    <span></span>
    <span>b</span>
  </span>
</div>

现在div直接没有任何文本,但它是孩子们的。如何查看整个div中是否有任何文字?

Now the div directly doesn't have any text, however it's children have. How can I check if there is any text in the whole div?

修改:

显然我在其中一个跨距中有一个&#8203; 字符,我知道这是一个零宽度的空白区域。所以基本上即使没有文本,jQuery text()也会将其作为一个并返回false。

Apparently I have a &#8203; character in one of the spans, which I know is a zero width white-space. So basically even though there is no text, the jQuery text() finds it as one and returns false.

我如何解决这个问题?

推荐答案

遍历myElement的所有后代并检查它们的html()。如果值不为空则递归迭代该对象。

iterate through all the descendants of myElement and check their html(). if the value is not empty "" then iterate that object recursively.

$( "#myElement" ).find( "*" ).each( function(){

   var $element = $(this);
   if ( $.trim( $element.html() ).length == 0 )
   {
     $element.remove();
   }

});

这篇关于检查DOM元素和子元素是否包含任何文本[JS或jQuery]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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