0

My html markup can look as following:

<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 -->

Is there a way to check if the h2-element itself or the h2-element with n-children nodes contains any html-content.

So far I have tried

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

EDIT: Just to clarify, I want this code working for every h2. The number of children nodes/nested children nodes within the h2-node is unknown.

pbaldauf
  • 1,671
  • 2
  • 23
  • 32

4 Answers4

3

What about :empty?

if ($('h2').is(':empty')) {...}
pavel
  • 26,538
  • 10
  • 45
  • 61
2

Just check if the element you want has children and also check if has any text value.

$('h2').children().length === 0 && !$('h2').text();
ianaya89
  • 4,153
  • 3
  • 26
  • 34
1

Use jQuery's .text() instead of .html():

 if ( $('h2').text().length )
Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
0

You can even use:

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

This works for text nodes too!

$(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>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252