Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
-1
rated 0 times [  6] [ 7]  / answers: 1 / hits: 37512  / 12 Years ago, fri, august 17, 2012, 12:00:00

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 :



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


And here's the JS code :



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


But when i alert parentHTML i get the same old string.


More From » regex

 Answers
9

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.



References:




[#83567] Thursday, August 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryantc

Total Points: 455
Total Questions: 96
Total Answers: 110

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
bryantc questions
Fri, Aug 13, 21, 00:00, 3 Years ago
Tue, Mar 30, 21, 00:00, 3 Years ago
Fri, Jun 5, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;