JavaScript HTML DOM - Changing HTML


JavaScript can modify the content of HTML elements using the HTML DOM.


Changing HTML Content

The simplest way to change the content of an HTML element is by using the innerHTML property.

To modify the content of an HTML element, follow this syntax:

document.getElementById(id).innerHTML = new HTML

This illustration modifies the text within a <p> element.

Example explained:

  • The HTML code shown above has a <p> element with the attribute id="p1".
  • We employ HTML DOM to retrieve the element identified as id="p1".
  • A piece of JavaScript code updates the content inside an element by modifying the innerHTML to display "New text!"

This example modifies what is inside an <h1> element.

Example explained:

  • The provided HTML document has an <h1>element with the attribute id="id01".
  • We utilize HTML DOM to retrieve the element with the id="id01".
  • A piece of JavaScript code updates the content inside an element, specified by the innerHTML attribute, and sets it to "New Heading".

Changing the Value of an Attribute

To modify an HTML attribute's value, follow this syntax.

document.getElementById(id).attribute = new value

This sample demonstrates how to modify the src attribute value of an <img> element.

Example explained:

  • The provided HTML document has an<img> element with theid="myImage".
  • We utilize HTML DOM to access the element identified as id="myImage".
  • A piece of JavaScript code modifies the src attribute of an element, changing it from "smiley.gif" to "landscape.jpg."

Dynamic HTML content

JavaScript has the ability to generate dynamic HTML content.

id="today">Date : Tue Jan 23 2024 20:08:03 GMT+0500 (Pakistan Standard Time)


document.write()

In JavaScript, you can use document.write() to write content directly to the HTML output stream.

Avoid using document.write() once the document has finished loading, as it will overwrite the existing document.