Jump to content

div.innerHTML.replace("<p></p>",""); does not work


pstein

Recommended Posts

I wanted to replace on a given webpage ALL empty paragraphs

 

<p></p>

 

or (mind the blank!)

 

<p> </p>

 

by nothing. Therefore I coded:

 

var div = document.getElementById("foobar");

div.innerHTML = div.innerHTML.replace("<p></p>","");

 

....but it doesn't work.

 

What do I have to change?

 

Furthermore I guess only the first occurence is changed. How do I replace ALL occurencies?

 

Thank you

Peter

 

Link to comment
Share on other sites

One way would be is to get all the p elements inside the div element with the id of 'foobar' like:

 

var div = document.getElementById("foobar");

var pElems = div.getElementsByTagName("P");

 

pElems will contain all the p elements that are inside the foobar div. You'd then loop through all them and check if the innerHTML of the p element is empty or not. If it is empty, you can use the removeChild() method to remove the empty p element from its parent, the foobar div.

Link to comment
Share on other sites

Looks like a fun problem. Why can't you do something like...

var list = document.getElementsByTagName('p');var len = list.length;for(var i=len-1 ; i>=0 ; i--){if(list[i].innerHTML.trim==''){list[i].parentNode.removeChild(list[i]);}}
Link to comment
Share on other sites

The trouble in using for loop is that as you remove each empty paragraph it kinder screws up the index reference to the remaining, so it might be better to check each paragraph with while loop, from top if empty remove, if not proceed to next, the len variable is problem also it set to original length before processing, this also changes so you will end up with undefined errors as it trys to index paragraphs that outside its original scope because they have been removed.

var parentelem = document.getElementById("foobar");            var childelem = parentelem.getElementsByTagName("p");            var elem_progression_count=0;            while (elem_progression_count < childelem.length){                if(childelem[elem_progression_count].childNodes.length==0)                {                    childelem[elem_progression_count].parentNode.removeChild(childelem[elem_progression_count])                  }                else                {                    elem_progression_count++;                    }}
Edited by dsonesuk
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...