JavaScript HTML DOM Content

Back to JS page

Table of Contents

Changing HTML Content

The easiest way to change 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 text

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM Content</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Changing HTML Content</h4>
<p id="demo">Original text</p>
<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hello JavaScript!'">Click Me!</button>

</body>
</html>

Example 1

Result View Example

The innerHTML Property

The innerHTML property can be used to get or change any HTML element, including <html> and <body>:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM Content</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>The innerHTML Property</h4>
<p id="demo1">First paragraph</p>
<p id="demo2">Second paragraph</p>

<script>
document.getElementById("demo1").innerHTML = "Content changed!";
document.getElementById("demo2").innerHTML = "<b>Bold text</b> with HTML tags";
</script>

</body>
</html>

Example 2

Result View Example

Changing an Attribute

To change an HTML attribute, use this syntax:

document.getElementById(id).attribute = new value

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM Content</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Changing an Attribute</h4>
<img id="image" src="https://www.w3schools.com/js/pic_bulboff.gif" width="100" height="180">
<p>
<button type="button" onclick="document.getElementById('image').src='https://www.w3schools.com/js/pic_bulbon.gif'">Turn on the light</button>
<button type="button" onclick="document.getElementById('image').src='https://www.w3schools.com/js/pic_bulboff.gif'">Turn off the light</button>
</p>

</body>
</html>

Example 3

Result View Example

Dynamic HTML content

JavaScript can create dynamic HTML content:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM Content</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Dynamic HTML content</h4>
<p id="demo"></p>

<script>
const date = new Date();
document.getElementById("demo").innerHTML = "Today's date: " + date;
</script>

</body>
</html>

Example 4

Result View Example

document.write()

The document.write() method can be used to write directly to the HTML output stream:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM Content</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>document.write()</h4>
<p>Note: document.write() clears the document if used after the document has loaded.</p>

<script>
document.write("Hello from document.write!");
</script>

</body>
</html>

Example 5

Result View Example

Document

Document in project

You can Download PDF file.

Reference