JQuery 节点检查是否不为空

JQuery Node check if not empty

本文关键字:是否 节点 检查 JQuery      更新时间:2023-09-26

我的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 个子节点h2元素是否包含任何 html 内容。

到目前为止我已经尝试过

 if ( $('h2').html() !== '' ) ...
 if ( $('h2 *').html() !== '' ) ...
 if ( $('h2').html().length ) ...

编辑:只是为了澄清,我希望这段代码适用于每个h2h2 节点中的子节点/嵌套子节点的数量未知。

:empty呢?

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

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

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

使用 jQuery 的 .text() 而不是 .html()

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

您甚至可以使用:

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>