HTML DOM - Changing HTML
The HTML DOM allows JavaScript to change both the text and the content of HTML elements.
Changing HTML Content
The HTML DOM allows JavaScript to change both the text and the content of HTML elements.
The easiest way to modify the content is by using the innerHTML property:
document.getElementById(id).innerHTML = new HTML
The innerHTML Property
The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.
Common Mistakes
- Trying to access a DOM element before it exists
- Forgetting the quotes in an id like "demo"
Example
Example Code
htmlHello World!
document.getElementById("p1").innerHTML = "New text!";Example explained:
- The HTML document above contains a
element with id="p1" - We use the HTML DOM to get the element with id="p1" - A JavaScript changes the content (innerHTML) of that element to "New text!" ### Example ``html # Old Heading const element = document.getElementById("id01"); element.innerHTML = "New Heading"; `` Example explained:
- The HTML document above contains an element with id="id01"
- We use the HTML DOM to get the element with id="id01"
- A JavaScript changes the content (innerHTML) of that element to "New Heading"
Changing an Attribute
To change the value of an HTML attribute, use this syntax:
document.getElementById(id).attribute = new value
Example
Example Code
htmldocument.getElementById("myImage").src = "landscape.jpg";Example explained:
- The HTML document above contains an element with id="myImage"
- We use the HTML DOM to get the element with id="myImage"
- A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg"
Dynamic HTML content
JavaScript can create dynamic HTML content:
Example
Example Code
htmldocument.getElementById("demo").innerHTML = "Date : " + Date();document.write()
In JavaScript, document.write() can be used to write directly to the HTML output stream:
Example
Example Code
htmlBla bla bla
document.write(Date());
Bla bla blaWarning !
Never use document.write() after the document is loaded. It will overwrite the document.
Interactive Code Examples
JS Example 1
htmlJS Example 2
htmlJS Example 3
htmlJS Example 4
html<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("demo").innerHTML = "Date : " + Date();
</script>
</body>
</html>