Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove empty p tags with jQuery?

Tags:

jquery

The platform I'm building a website on produces empty p tags in wysiwyg mode. How can I take these out?

Something like this, perhaps...

$("<p> </p>").remove();

Although the code above does nothing.

like image 959
Steve Avatar asked May 23 '11 04:05

Steve


People also ask

How do I remove the blank P tag?

* Removes empty paragraph tags from shortcodes in WordPress. add_filter( 'the_content' , 'tg_remove_empty_paragraph_tags_from_shortcodes_wordpress' ); That's it! All empty paragraph tags have been removed from your shortcodes.

Is empty in jQuery?

The empty() method removes all child nodes and content from the selected elements. Note: This method does not remove the element itself, or its attributes. Tip: To remove the elements without removing data and events, use the detach() method. Tip: To remove the elements and its data and events, use the remove() method.

What is the difference between Remove and empty methods in jQuery?

empty() will empty the selection of its contents, but preserve the selection itself. remove() will empty the selection of its contents and remove the selection itself.

How check Div is empty or not in jQuery?

Method 1: Using the “:empty” selector: The element to be checked using is() method. The is() method is used to check if one of the selected elements matches to the selector element. This method can be used on this element to test if it is empty by using “:empty” selector.


2 Answers

The answer depends on what "empty" means. If the empty paragraphs are <p></p> then fireeyedboy's p:empty selector is the way to go. If there could be spaces or newlines or other such things then you'll probably want something like this:

$('p').each(function() {     const $this = $(this);     if($this.html().replace(/\s|&nbsp;/g, '').length === 0)         $this.remove(); }); 

Example: http://jsfiddle.net/ambiguous/7L4WZ/

FCKEditor (not sure about CKEditor or TinyMCE) likes to add <p>&nbsp;</p> to the HTML so you might need the above somewhat ugly approach.

like image 69
mu is too short Avatar answered Sep 26 '22 17:09

mu is too short


Try:

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

like image 20
Decent Dabbler Avatar answered Sep 23 '22 17:09

Decent Dabbler