简体   繁体   中英

How do I start a new line in Javascript without using document.write()?

 var infoDiv = document.getElementById("info"); console.log(window); console.log(window.location); infoDiv.textContent += "The URL of this page is " + window.location.href; // i am hoping the following sentence can start in a new line infoDiv.textContent += "The user agent is " + window.navigator.userAgent; 

I tried document.write("\\n") as people suggested here , but Chrome gives me this violation warning:

[Violation] Avoid using document.write(). https://developers.google.com/web/updates/2016/08/removing-document-write

What should I do? Thanks!

Line breaks in HTML are created with the <br> element (generally between text nodes). Paragraphs with the <p> element (generally around text nodes).

In either case you'll need to stop twiddling textContent because it will wipe out any elements you create.

Use document.createElement , document.createTextNode , and infoDiv.appendChild .

You can append elements instead of text:

var infoDiv = document.getElementById("info");
infoDiv.append("The URL of this page is " + window.location.href);
// append new line
infoDiv.append(document.createElement('br'));
infoDiv.append("The user agent is " + window.navigator.userAgent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM