Remove empty p tags from an element and remove any p tags around an element (image in this case)

by andyjh07

HTML

<div id="banner">
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p><img src="test.jpg"/></p>
</div>

CSS

p { background: #f00; }

JavaScript

$(document).ready(function(){
    $('#banner > p').each(function() {
        $('#banner > p:empty').remove();
        var $this = $(this);
        if($this.html().replace(/\s|&nbsp;/g, '').length == 0)
            $this.remove();
    });   
    // This forces any images wrapped in p tags to be removed from the p tags and displayed normally
    $('p img').closest('p > *').unwrap();
});