Remove every white space between tags using JavaScript

前端 未结 5 1589
你的背包
你的背包 2020-12-30 06:57

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 :

  • 5条回答
    •  一生所求
      2020-12-30 07:13

      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+\

      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+<");
      firstName.parentNode.innerHTML = parentHTML;
      
      console.log(firstname, parentHTML);​
      

      JS Fiddle demo.

      References:

      • JavaScript Regular Expressions.

    提交回复
    热议问题