JQuery Node检查是否为空

时间:2014-11-13 12:50:21

标签: javascript jquery html

我的 html标记可能如下所示:

<h2></h2> <!-- empty -->
<h2>text</h2> <!-- not empty -->
<h2><p>text</p><h2> <!-- not empty -->
<h2><p></p>/<h2> <!-- empty -->
<h2><p><span></span></p></h2> <!-- empty -->

有没有办法检查h2 - 元素本身或带有 n-children节点的<{1}} - 元素是否包含任何 html -content。

到目前为止,我已经尝试了

h2

编辑:为了澄清,我希望此代码适用于每个 h2 h2 -node中的子节点/嵌套子节点数未知。

4 个答案:

答案 0 :(得分:3)

:empty怎么样?

if ($('h2').is(':empty')) {...}

答案 1 :(得分:2)

只需检查您想要的元素是否有子元素,并检查是否有任何文本值。

$('h2').children().length === 0 && !$('h2').text();

答案 2 :(得分:1)

使用jQuery&#39; .text()代替.html()

 if ( $('h2').text().length )

答案 3 :(得分:0)

您甚至可以使用:

if ($("h2").html().trim().length == 0) {...}

这也适用于文本节点!

$(document).ready(function(){
  $("h2").each(function(){
    if ($(this).html().trim().length == 0)
      $("#result").append("Empty<br />");
    else
      if ($(this).text().trim().length == 0)
        $("#result").append("Empty<br />");
      else
        $("#result").append("Not Empty<br />");
  });
});
* {font-family: 'Segoe UI', sans-serif;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<h2></h2> <!-- empty -->
<h2>text</h2> <!-- not empty -->
<h2><p>text</p></h2> <!-- not empty -->
<h2><p></p></h2> <!-- empty -->
<h2><p><span></span></p></h2> <!-- empty -->

<div id="result"></div>