Why doesn't javascript newlines work inside html?

后端 未结 13 2548
梦谈多话
梦谈多话 2020-12-06 12:08

So I have the following:


  
    
  
<         


        
相关标签:
13条回答
  • 2020-12-06 12:56

    When HTML renders, it ignores whitespace. Thus the only way is to use line breaks.

    Use <br/> instead of \n and it will work fine

    The document.write() function writes HTML into the element.

    0 讨论(0)
  • 2020-12-06 12:57

    When you write to the page, you're not writing JavaScript; you're writing HTML. \n is a special "line feed" character that doesn't create a line break in the browser's rendering of the HTML. It WILL create a line break in the HTML file itself, but the browser doesn't take this into consideration when it renders out the markup.

    Thus, the br tag is required.

    0 讨论(0)
  • 2020-12-06 12:59

    Everyone has said what it was to be said but in case if you are using firebug/chrome Javascript console ..then try this >

    console.log("Hello\nWorld");

    This is the key difference. When you are printing something in HTML, the HTML rules apply. Elsewhere you can see the line breaks work.

    0 讨论(0)
  • 2020-12-06 13:00

    Whitespace emitted by JavaScript works like any other whitespace in your HTML file. That seems the expected behavior to me.

    0 讨论(0)
  • 2020-12-06 13:02

    I had:

    <div>Hello\nworld</div>
    

    I added the below css to div class and it's working now:

    div {
          white-space: pre-wrap;
      }
    

    I hope this solve your problem too.

    0 讨论(0)
  • 2020-12-06 13:02

    Use <pre></pre> on the html and it will respect the text format from JS.

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