MyInternships.in

HTML DOM

HTML DOM writeln() Method

The writeln() method writes one or more strings to the document, just like write(), but adds a newline character after the text. It is a legacy way of injecting content directly into the page stream.


Definition and Usage

document.writeln(text) writes the given text into the document and appends a newline (\n) character. Because HTML collapses whitespace, the newline usually has no visual effect unless the output is inside a <pre> element, where whitespace is preserved.

Like document.write(), calling writeln() after the page has finished loading will clear the entire page and replace it with the new output.

Syntax

document.writeln(text)

Example

Inside a <pre> element, the newline added by writeln() is visible. Each line appears on its own row.

writeln inside a pre block
Example
<!DOCTYPE html>
<html>
<body>
  <pre>
  <script>
    document.writeln("Line one");
    document.writeln("Line two");
    document.writeln("Line three");
  </script>
  </pre>
</body>
</html>

More Examples

Outside a <pre> element the newline is collapsed, so writeln() looks the same as write(). This demo prints numbers 1 to 5.

writeln in a loop
Example
<!DOCTYPE html>
<html>
<body>
  <script>
    for (let i = 1; i <= 5; i++) {
      document.writeln("Number " + i + " ");
    }
  </script>
</body>
</html>
⚠️

writeln() is a legacy method. Calling it after page load erases the page, and it does not work with XHTML. Prefer building DOM nodes with createElement in modern code.

Key Takeaways

  • writeln() writes text plus a trailing newline character.
  • The newline is only visible inside <pre> elements.
  • It behaves like write() otherwise.
  • Calling it after load replaces the whole page - avoid in new code.

Related HTML Topics

Keep learning with these closely related tutorials.

Ready to use your HTML skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships