JavaScript HTML DOM - Changing HTML


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


Changing HTML Output Stream

JavaScript can create dynamic HTML content:

Today's date is:

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

Examples

<!DOCTYPE html>
<html>
<body>

<script>
document.write(Date());
</script>

</body>
</html>

Try it Yourself »

lamp Never use document.write() after the document (DOM) has finished loading. It will overwrite the document.


Changing HTML Content

The simplest way to modify HTML content is to use the innerHTML attribute.

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

document.getElementById(id).innerHTML=new HTML

This example changes the content of a <p> element:

Examples

<html>
<body>

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML="New text!";
</script>

</body>
</html>

Try it Yourself »

This example changes the content of an <h1> element:

Examples

<!DOCTYPE html>
<html>
<body>

<h1 id="header">Old Header</h1>

<script>
var element=document.getElementById("header");
element.innerHTML="New heading";
</script>

</body>
</html>

Try it Yourself »

Example explanation:

  • The HTML document above contains an <h1> element with id="header"

  • We use HTML DOM to get the element with id="header"

  • JavaScript changes the content of this element (innerHTML)


Changing HTML Attributes

To change an attribute of an HTML element, use this syntax:

document.getElementById(id).attribute=new attribute value

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

Examples

<!DOCTYPE html>
<html>
<body>

<img id="image" src="smiley.gif.html">

<script>
document.getElementById("image").src="landscape.jpg.html";
</script>

</body>
</html>

Try it Yourself »

Example explanation:

  • The HTML document above contains an <img> element with id="image"
  • We use HTML DOM to get the element with id="image"
  • JavaScript changes the attribute of this element (changes "smiley.gif" to "landscape.jpg")
Other extensions