Rafael Adel Rafael Adel - 7 days ago 4x
Javascript Question

Remove every white space between tags using JavaScript

I'm trying to remove white space between tags so that childNodes only contain those tags nodes not the white space nodes too. Here's my code :

<label for="firstName" class="mainLabel">First Name : </label>
<input type="text" name="firstName" id="firstName"/>
<span>This must be filled</span>

And here's the JS code :

var parentHTML = firstName.parentNode.innerHTML;
parentHTML = parentHTML.replace(/>\n</g,"><");
firstName.parentNode.innerHTML = parentHTML;

But when i alert
i get the same old string.


It's (not, see after the rule) because strings are immutable, I think, and you're setting the innerHTML of the parent element to be the exact same string you retrieved from it earlier.

Instead, I'd suggest:

var firstname = document.getElementsByTagName('input')[0],
    parentHTML = firstname.parentNode.innerHTML,
    newHTML = parentHTML.replace(/\>\s+\</g,'');
firstname.parentNode.innerHTML = newHTML;

console.log(parentHTML, newHTML, (parentHTML == newHTML));

JS Fiddle demo.

With regards to the comment from jfriend00 (below), it seems the regular expression was the problem, the \n didn't match the supplied pattern, that being the case, the following amendment satisfies teh requirements:

var firstname = document.getElementsByTagName('input')[0],
    parentHTML = firstName.parentNode.innerHTML;
parentHTML = parentHTML.replace(/>\s+</g, "><");
firstName.parentNode.innerHTML = parentHTML;

console.log(firstname, parentHTML);‚Äč

JS Fiddle demo.