Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14
Chapter 6

Changing HTML Content & CSS Styles

document.write(), the innerHTML property, and changing styles via the DOM.


Writing to the HTML Output Stream — document.write()

  • Outputs text directly into the HTML stream during page load.
  • Can include HTML tags for formatting.
  • Warning: calling it after the page has loaded overwrites the entire page.
document.write("Hello World!");        // plain text
document.write("<h1>Hello!</h1>");    // renders as an H1 heading

Changing HTML Content — the innerHTML Property

The easiest way to get or set element content. It can change any HTML element, including <html> and <body>, and is preferred over document.write() for changes after page load.

<p id="demo">Hello World!</p>
<script>
  // Replace the paragraph content
  document.getElementById("demo").innerHTML = "New text!";
</script>

Changing CSS Styles via the DOM

Syntax: document.getElementById(id).style.property = "value".

// Change text colour and font size
document.getElementById("p1").style.color = "red";
document.getElementById("p1").style.fontSize = "xx-large";

// Hide or show an element
document.getElementById("myDiv").style.display = "none";   // hide
document.getElementById("myDiv").style.display = "block";  // show

// Change the page background
document.body.style.backgroundColor = "#f0f4f8";

Activity — complete the code

Complete the code correctly to mark this lesson as complete automatically.

Complete the content and style changes.

// Write into the output stream during page load
document.("<h1>Hello!</h1>");
 
// Replace an element content
document.getElementById("demo"). = "New text!";
 
// Change a CSS style
document.getElementById("p1").style. = "red";
 
// Hide an element
document.getElementById("myDiv").style. = "none";