Search w3schools.com:

SHARE THIS PAGE

JavaScript HTML DOM - Changing HTML


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


Changing the HTML Output Stream

JavaScript can create dynamic HTML content:

Date:

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

Example

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

Try it yourself »

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


Changing HTML Content

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

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

Example

<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:

Example

<!DOCTYPE html>
<html>
<body>

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

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

</body>
</html>

Try it yourself »

Example explained:

  • The HTML document above contains an <h1> element with id="header"
  • We use the HTML DOM to get the element with id="header"
  • A JavaScript changes the content (innerHTML) of that element

Changing an HTML Attribute

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

document.getElementById(id).attribute=new value

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

Example

<!DOCTYPE html>
<html>
<body>

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

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

</body>
</html>

Try it yourself »

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"
  • A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg"



W3Schools Certification

W3Schools' Online Certification

The perfect solution for professionals who need to balance work, family, and career building.

More than 10 000 certificates already issued!

Get Your Certificate »

The HTML Certificate documents your knowledge of HTML.

The HTML5 Certificate documents your knowledge of advanced HTML5.

The CSS Certificate documents your knowledge of advanced CSS.

The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.

The jQuery Certificate documents your knowledge of jQuery.

The XML Certificate documents your knowledge of XML, XML DOM and XSLT.

The ASP Certificate documents your knowledge of ASP, SQL, and ADO.

The PHP Certificate documents your knowledge of PHP and SQL (MySQL).

Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]