Inserting a newline into a pre tag (IE, Javascript)

前端 未结 11 1831
走了就别回头了
走了就别回头了 2020-12-10 12:34

In IE when I insert text into a

 tag the newlines are ignored:





        
相关标签:
11条回答
  • 2020-12-10 12:41

    I've found that innerHTML is processed before it is applied to the element, hence <br> becomes a newline and multiple white spaces are removed.

    To preserve the raw text you must use nodeValue, for example;

    document.getElementById('pre_id').firstChild.nodeValue='    white space \r\n ad new line';
    
    0 讨论(0)
  • 2020-12-10 12:44

    Content inside the <pre> tag should not be considered HTML.

    In fact, the point of <pre> tag is so that it does display formatted text.

    Using the innerText property is the correct way to modify the content of a <pre> tag.

    document.getElementById("putItHere").innerText = "first line\nsecond line";
    
    0 讨论(0)
  • 2020-12-10 12:46

    These quirksmode.org bug report and comments about innerHTML behaviour of Internet Explorer could help:

    "IE applies HTML normalization to the data that is assigned to the innerHTML property. This causes incorrect display of whitespace in elements that ought to preserve formatting, such as <pre> and <textarea>."

    0 讨论(0)
  • 2020-12-10 12:46

    Does this work in IE?

    document.getElementById("putItHere")
        .appendChild(document.createTextNode("first line\nsecond line"));
    

    I tested it with Firefox and it works. :-)

    0 讨论(0)
  • 2020-12-10 12:46

    The workaround can be found in the page linked to in the accepted answer. For ease of use here it is:

    if (elem.tagName == "PRE" && "outerHTML" in elem)
    {
        elem.outerHTML = "<PRE>" + str + "</PRE>";
    }
    else
    {
        elem.innerHTML = str;
    }
    
    0 讨论(0)
  • 2020-12-10 12:52

    <br/> shoud only output one line in all browsers. Of course remove the \n as well, code should be:

    document.getElementById("putItHere").innerHTML = "first line<br/>second line";
    
    0 讨论(0)
提交回复
热议问题