DOM HTML

The HTML DOM allows a user with the help of JavaScript to change or modify the content of HTML elements.


Changing/Modifying the HTML Output Stream

With the help of JavaScript, we can create HTML content dynamically:

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

Input:-
<!DOCTYPE html>
<html>
   <body>
      <script>
         document.write(Date());
      </script>
   </body>
</html>

Output :-

Note:- Never use document.write() after when the document is loaded. It will overwrite the document content.


Changing/ Modifying HTML Content

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

Below is the syntax to change the content of an HTML element –

document.getElementById(id).innerHTML = your HTML

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

Input:-
<html>
   <body>
      <span id="span1">Hello World!</span>
      <script>
         document.getElementById("span1").innerHTML = "My new content.";
      </script>
   </body>
</html>

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 a <h2> element:

Input:-
<html>
   <body>
      <h2 id="h2">Hello World!</h2>
      <script>
         document.getElementById("h2").innerHTML = "My New Heading.";
      </script>
   </body>
</html>

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, use this syntax:

document.getElementById(id).attribute = my value

The below example changes the src attribute of an <img> element:

Input:-
<!DOCTYPE html>
<html>
   <body>
      <img id="image" width="200" src="https://image.shutterstock.com/image-vector/sun-icon-vector-jpg-jpeg-260nw-414560821.jpg">
      <script>
         document.getElementById("image").src = "https://static.bhphotovideo.com/explora/sites/default/files/ts-photographing-the-moon.jpg";
      </script>
      <p>The original image was sun.jpg, but script changed it to moon.jpg</p>
   </body>
</html>

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”