Reputation: 3791
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
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
Reputation: 64419
While @NULL may be right about the id's, it can only work if the <p>
is actually empty:
<div>
<p id="contentempty">
Hello
</p>
</div>
<div>
<p id="contentempty"></p>
</div>
Upvotes: 1
Reputation: 589
<div>
<p class="contentempty">
Hello
</p>
</div>
<div>
<p class="contentempty"></p>
</div>
JS:
$('.contentempty:empty').parent().remove();
Upvotes: 2