Rad
Rad

Reputation: 391

Removing empty paragraph tags

I would like to find the simplest way to trim the empty

tags before any text starts. for example i have the below text.

<p> </p><p> </p>
<p> </p><p>     </p>
<p>    </p>
<p>This is an example<br></p><p> </p><p>continue </p>

I would like the output to be <p>This is an example<br></p><p> </p><p>continue </p>

I want all the empty P tags to be removed. There can be more than one space between

tags.

I have the options to use CSS or VB or c#.

Upvotes: 3

Views: 5852

Answers (5)

Issac Johnson
Issac Johnson

Reputation: 146

Please try this

   function removeEmptyPTags() {            
                var items = $('body').find('p');
                $.each(items, function (i, v) {
                    if ($(items[i]).html().trim() === "") {
                        $(items[i]).remove();
                    }
                });
            }

Upvotes: -1

Imad
Imad

Reputation: 7490

using jQuery, NOT c#, vb.net or CSS

write this on document ready event

var p = $("p"); 

    for (var i = 0; i < p.length; i++)
   { 
       if($.trim(p[i].innerHTML) == "")
        {
          p[i].remove();
         }
    }
  1. Find all P tag
  2. iterate over them to find empty tags
  3. remove them

JSFiddle

Upvotes: -1

Marco
Marco

Reputation: 23945

Give your comment, that you also accept C# I'd suggest using a simple regular expression to validate this:

var source = @"<p> </p><p> </p>
<p> </p><p>     </p>
<p>    </p>
<p>This is an example<br></p><p> </p><p>continue </p>";

string output = Regex.Replace(source, @"<p>\s*</p>", "").Trim();

The same code in VB.net converted with Telerik should look like this:

Dim source = "<p> </p><p> </p>" & vbCr & vbLf & "<p> </p><p>     </p>" & vbCr & vbLf & "<p>    </p>" & vbCr & vbLf & "<p>This is an example<br></p><p> </p><p>continue </p>"

Dim output As String = Regex.Replace(source, "<p>\s*</p>", "").Trim()

Explanation:

<p> matches the characters <p> literally
\s* match any white space character [\r\n\t\f ] 0 to unlimited times
</p> matches the characters </p> literally

Upvotes: 4

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

You have tagged your question in css. So, I'm providing you an answer in css using :empty pseudo class selector:

p:empty{
  display: none;
}

See can I use :empty


As per your updated question:

you can use not like below:

p:empty :not(p + p:empty){
   display: none;
}

Upvotes: 6

Dima
Dima

Reputation: 287

I think this css trick will work:

p:empty {
    display: none;
}

Upvotes: -1

Related Questions