Jump to content

How to delete all <P> elements containing whitespaces only?


pstein

Recommended Posts

First, get all <p> elements.

var elements = document.getElementsByTagName("p");

Then, loop through all of them. This has to be done in reverse order because deleting items reindexes the elements node list we obtained. (If you want to learn more about this I can explain it in more detail)

var element;
for(var i = elements.length-1; i >= 0; i--) {
  element = elements[i];
  ...

For each element in the loop, check its contents. This is the complicated part. You have to remove all <br> elements and whitespace from the element's innerHTML and check whether the result is empty. If it was just normal whitespace, the trim() method would be enough, but you wanted to check for <br> and &nbsp; so we need a regular expression.

var contents = element.innerHTML;
contents = contents.replace(/(<br[^>]>|&nbsp;|\s|\n|\r|\t)+/gi, "");
if(contents.length === 0) {
  element.parentNode.removeChild(element);
}

 

Link to comment
Share on other sites

Requirements are, if you missed them

23 hours ago, pstein said:

How can I (after loading of webpage) remove with JavaScript/jQuery ALL <P> elements which contain whitespaces only?

The code should match for example the following elements:


<P><br></P>

 


<P><br><br></P>

 


<P><br class="foobar">&nbsp;</P>

 

If you want to change goal posts to not include those elements, i can easily check by using .has() to not include them.

Link to comment
Share on other sites

On 2/18/2021 at 9:54 PM, dsonesuk said:

Can't you just search for any text(), no text remove(), doesn't matter if any elements exist


$(document).ready(function(){
  
    $("p").each(function(){
    if($(this).text().trim() ==""){
    $(this).remove();
 }
});
});

 

Thank you for the suggestion.

The problem is here that <P> could contain (only) <img> elements. And <img> are not text elements. So
 

<p>
<img src=".......>...</img>
</p>

would be deleted with your javascript.

Thats not intended

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...