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.

3
  • 2
    See here: stackoverflow.com/questions/6813227/… Commented Nov 13, 2014 at 12:51
  • As Moshikaro said, look there and don't forget to check about children $elem.children().length == 0 Commented Nov 13, 2014 at 12:56
  • 1
    I have created jsfiddle demo, please check here Commented Nov 13, 2014 at 13:16

4 Answers 4

3

What about :empty?

if ($('h2').is(':empty')) {...}
Sign up to request clarification or add additional context in comments.

1 Comment

:empty is bad in FF, Safari
2

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

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

2 Comments

This won't work for text nodes... <h2>text</h2>
@RGraham you are right, I've updated the answer.
1

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

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

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.