twsJames
twsJames

Reputation: 425

JQuery - improving my function

I have a client who uses a WYSIWYG editor to create new website pages. The problem is that sometime the WYSIWYG editor put in empty p tags

<p>&nbsp;</p>

This was causing havoc with the layout so i wrote a little function to remove these empty tags

$('p')
.filter(function() {
   return $.trim($(this).text()) === ''
})
.remove()

The problem now is that when a image is inserted into the wysiwyg editor it get's included in a p tag and my function removes it from the screen.

Can either my function be updated to allow images or can I just search for and remove empty p tags???

Thanks in advance

James

Upvotes: 0

Views: 87

Answers (6)

Ernestas Stankevičius
Ernestas Stankevičius

Reputation: 2493

Just fix WYSIWYG, if it is javascript, if not, then fix at backend not frontend.

Upvotes: 1

marissajmc
marissajmc

Reputation: 2603

How about this

$('p').each(function(){
    if($(this).html() == "&nbsp;"){
        $(this).remove();  
    }
});

Demo: http://jsfiddle.net/krVBd/

Upvotes: 1

jmar777
jmar777

Reputation: 39649

You could make your filter also ensure that there are no child elements:

$('p').filter(function() {
    var $this = $(this);
    return !$this.children().length && $.trim($this.text()) === '';
}).remove()

Upvotes: 2

David Thomas
David Thomas

Reputation: 253318

$('p').not(':has("img")')
.filter(function() {
   return $.trim($(this).text()) === ''
})
.remove()

JS Fiddle demo.

Upvotes: 1

James Allardice
James Allardice

Reputation: 165971

You can use the :empty pseudo-selector to only select elements that have no children:

$("p:empty").remove();

However, if you have p elements with white-space and nothing else they will not be removed (because :empty treats text nodes as children). So you may want to remove white space (using .trim) from your p elements before running the above.

The problem with your current method is that tags like img do not contain any text, so your filter function thinks a p element containing only an img element should be removed.

Upvotes: 2

tehdoommarine
tehdoommarine

Reputation: 2068

You can try using div tags around the blocks you want removed such as . In your jQuery statement you can then call based off the div id instead of all paragraphs.

Upvotes: 0

Related Questions