Javascript Removing Whitespace When It Shouldn't?

前端 未结 10 2036
谎友^
谎友^ 2020-12-11 05:29

I have a HTML file that has code similar to the following.


&         
相关标签:
10条回答
  • 2020-12-11 05:32

    If someone could format my last post correctly it would look more readable. Sorry, I messed that one up. Basically the trick is create create a throwaway pre element, then append a copy of your node to that. Then you can get innerText or textContent depending on the browser.

    All browsers except IE basically do the obvious thing correctly. IE requires this hack since it only preserves white-space in pre elements, and only when you access innerText.

    0 讨论(0)
  • 2020-12-11 05:32

    This following trick preserves white-space in innerText in IE

    var cloned = element.cloneNode(true);
    var pre = document.createElement("pre");
    pre.appendChild(cloned);
    var textContent = pre.textContent
      ? pre.textContent
      : pre.innerText;
    delete pre;
    delete cloned;
    
    0 讨论(0)
  • 2020-12-11 05:34

    The pre tag or white-space: pre in your CSS will treat all spaces as meaningful. This will also, however, turn newlines into line breaks, so be careful.

    0 讨论(0)
  • 2020-12-11 05:42

    This is a bit hacky, but it works on my IE.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
    <head>
        <title></title>
    </head>
    <body>
    <div id="a">a  b</div>
    <script>
    var a = document.getElementById("a");
    a.style.whiteSpace = "pre"
    window.onload = function() {
        alert(a.firstChild.nodeValue.length) // should show 4
    }
    </script>
    </body>
    </html>
    

    Some notes:

    • You must have a doctype.
    • You cannot query the DOM element before window.onload has fired
    • You should use element.nodeValue instead of innerHTML et al to avoid bugs when the text contains things like < > & "
    • You cannot reset whiteSpace once IE finishes rendering the page due to what I assume is an ugly bug
    0 讨论(0)
  • 2020-12-11 05:47

    HTML is white space insensititive which means your DOM is too. Would wrapping your "Hello World" in pre block work at all?

    0 讨论(0)
  • 2020-12-11 05:47

    In HTML,any spaces >1 are ignored, both in displaying text and in retrieving it via the DOM. The only guaranteed way to maintain spaces it to use a non-breaking space &nbsp;.

    0 讨论(0)
提交回复
热议问题
Hello World