Remove every white space between tags using JavaScript

前端 未结 5 1611
你的背包
你的背包 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:18

      I came across this thread because I was searching for a solution to eliminate gaps around divs caused by white space in HTML source, or line feeds in my case.

      Before I realized that white space could cause these gaps, I was going nuts trying to get rid of them. I want to keep my HTML source formatted for readability, so compressing the code is not a good solution for me. Even if I handled it this way, it doesn't fix divs that are generated by Google and other vendors.

      I started by creating the following function and calling it in body onload.

      function Compress_Html() {
          //Remove whitespace between html tags to prevent gaps between divs.
          document.body.innerHTML = document.body.innerHTML.replace( /(^|>)\s+|\s+(?=<|$)/g, "$1" );
      }
      

      This seemed to work perfectly, but unfortunately, it breaks the Google search box I have in my footer.

      After trying many variations of the regex pattern without success, I found this regex tester at http://www.regexpal.com/. I far as I can tell, the following pattern does what I need.

      ( /(^|>)[ \n\t]+/g, ">" )
      

      That said, the function was still breaking the search box. So I ended up moving it into a jQuery document ready function. Now it's working and does not break the search box.

      
      
      

    提交回复
    热议问题