2

jquery empty - remove html tag if no contents

How to remove html tag if it does not contain text or content.

if using <p></p> code is working, but if using

<p>

</p>

The code is not successful

jquery

$(document).ready(function(){
    $("button").click(function(){
        $('#demo p:empty').remove();
    });
});

html

<p>

</p>
==================================

$(document).ready(function(){
    $("button").click(function(){
		$('#demo p:empty').remove();
    });
});	 
  p {
    background:red;
    color:white;
    height:20px;
  }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>  
</head> 
<body>
  
<button>Run</button>	
<div id='demo'>
  <p>
  
  </p>
  <p>
    Lorem Ipsum .....
  </p>
</div>

</body>
</html>

Thank you in advance

2
  • What could possibly be within the <p></p>? Commented Mar 10, 2017 at 4:07
  • Just remove space from your <p> tag or before removing trim the value. Commented Mar 10, 2017 at 4:10

2 Answers 2

4

$(document).ready(function() {
  $("button").click(function() {
    $('#demo p').filter(function() {
      return $(this).html().trim().length == 0
    }).remove();
  });
});
p {
  background: red;
  color: white;
  height: 20px;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>demo</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>

<body>

  <button>Run</button>
  <div id='demo'>
    <p>

    </p>
    <p>
      Lorem Ipsum .....
    </p>
  </div>

</body>

</html>

  1. Use filter() with html() and trim()
  2. trim() to remove spaces
Sign up to request clarification or add additional context in comments.

1 Comment

@SisiSajah glad to help :)
0
$('#demo p').each(function(){
 if(!$(this).text() || !$(this).text().trim())
   $(this).remove();
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.