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

Changing HTML Content & CSS Styles

5 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

← Back to the full Chapter 6 deck

Changing HTML Content & CSS Styles
Fullscreen for presentation · Print / PDF for a handout
1 / 5
Lesson

Changing HTML Content & CSS Styles

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

Changing HTML Content & CSS Styles

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 & CSS Styles

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 HTML Content & CSS Styles

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";
Changing HTML Content & CSS Styles

Activity — complete the code

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";