Tim Wilkinson
Tim Wilkinson

Reputation: 3791

Remove parent div if <p> tag returns empty

I want to be able to remove the parent div of a p tag if the p tag is empty. I have given the p and id and used this line of code.

$('#contentempty:empty').parent().remove();

I have read through lots of documentation and this looks like it should be right, but when i jsfiddle it http://jsfiddle.net/timwilks13/78uQm/ it doesnt work. Anyone know what I am missing?! Thanks

Upvotes: 2

Views: 835

Answers (3)

Andreas Louv
Andreas Louv

Reputation: 47119

You can't have the same id multiple times on the same page, use classes instead:

<div>
  <p class="contentempty">
    Hello
  </p>
</div>
<div>
  <p class="contentempty">
  </p>
</div>

And JavaScript: (it is faster to use single selector .contentempty and then chain with jQuery.fn.filter)

$('.contentempty').filter(":empty").parent().remove();

You can make your own check for empty by using [jQuery.fn.map][2] and then check to see if the trimmed version of the innerHTML of the DOM Node is equal to empty string "":

$(".contentempty").map(function() {
     return !$.trim(this.innerHTML);
}).parent().remove();

Upvotes: 5

Nanne
Nanne

Reputation: 64419

While @NULL may be right about the id's, it can only work if the <p> is actually empty:

http://jsfiddle.net/sBpCB/

<div>
  <p id="contentempty">
    Hello
  </p>
</div>
<div>
  <p id="contentempty"></p>
</div>

Upvotes: 1

griffla
griffla

Reputation: 589

  1. Use classes instead of IDs (an ID must be unique)
  2. The Paragraph is not empty if there is white space.

http://jsfiddle.net/UNZTV/

<div>
  <p class="contentempty">
    Hello
  </p>
</div>
<div>
  <p class="contentempty"></p>
</div>

JS:

$('.contentempty:empty').parent().remove();

Upvotes: 2

Related Questions