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 loaddocument.("<h1>Hello!</h1>");// Replace an element contentdocument.getElementById("demo"). = "New text!";// Change a CSS styledocument.getElementById("p1").style. = "red";// Hide an elementdocument.getElementById("myDiv").style. = "none";