Changing HTML Content

The HTML DOM allows JavaScript to change the content of HTML elements.

The easiest way to modify the content of an HTML element is by using the innerHTML property.

To change the content of an HTML element, use this syntax:

document.getElementById(id).innerHTML = new HTML

EXAMPLE ❯


Changing the Value of an Attribute

To change the value of an HTML attribute, use this o change the value of an HTML attribute, use this syntax:

document.getElementById(id).attribute = new value

Example explained:

The HTML document below contains an <img> 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"

EXAMPLE ❯


Dynamic HTML content

JavaScript can create dynamic HTML content:

For Example:

Date : Sat Oct 23 2021 18:38:48 GMT+0530 (India Standard Time)

EXAMPLE ❯


document.write()

In JavaScript, document.write() can be used to write directly to the HTML output stream

Never use document.write() after the document is loaded. It will overwrite the document.

EXAMPLE ❯