JavaScript Tutorial

DOM HTML

The HTML DOM allows users to modify the content of HTML elements using JavaScript.

One way to dynamically create HTML content is by using the document.write() function in JavaScript. However, it is important to note that document.write() should not be used after the document is loaded, as it would overwrite the entire document content.

To change the content of an HTML element, the innerHTML property can be used. The syntax is as follows:

Output  :-

Note:- It is not recommended to use document.write() after the document is loaded, as it will overwrite the entire document content.

Changing/ Modifying HTML Content

To change the content of an HTML element, the innerHTML property can be used. The syntax is as follows:

document.getElementById(id).innerHTML = yourHTML;

The below example changes the content of an <span> element:

Input:-

Output :-

Example explained:

  • The above HTML document contains a <span> element with id="span1"
  • We use the HTML DOM to get the element with id="span1"
  • JavaScript modifies the content (innerHTML) of that element to "My new content."

The below example changes the content of an <h2> element:

Input:-

Output :-

Example explained:

  • The HTML document above contains an <h2> element with id="h2"
  • We use the HTML DOM to get the element with id="h2"
  • JavaScript modifies the content (innerHTML) of that element to "My New Heading"

Changing/modifying the Value of an Attribute

To modify the value of an HTML attribute, you can use the following syntax:

document.getElementById(id).attribute = myValue;

Here's an example that changes the src attribute of an <img> element:

Input:-

Output :-

Example explained:

  • The HTML document above contains an <img> element with id="image"
  • We use the HTML DOM to get the element with id="image"
  • JavaScript modifies the src attribute of that element from "sun.jpg" to "moon.jpg"
Go back to Previous Course