Categories
Web development

JavaScript HTML DOM/HTML

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

JavaScript HTML DOM/HTML

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:

<!DOCTYPE html>
<html>
<body>

<h4>JavaScript can change HTML.</h4>
<p id="example">Hello World!</p>

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

<p>The paragraph above was changed by a JavaScript.</p>

</body>
</html>

Output:

JavaScript can change HTML.

Hello World!

The paragraph above was changed by a JavaScript.


Example explained:

The HTML document above contains a <p> element with id=”example“. We use the HTML DOM to get the element with id=”example”. A JavaScript changes the content (innerHTML) of that element to “New text!”

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

<!DOCTYPE html>
<html>
<body>

<h3 id="example-2">Old Heading</h3>

<script>
var element = document.getElementById("example-2");
element.innerHTML = "New Heading";
</script>

<p>JavaScript changed "Old Heading" to "New Heading".</p>

</body>
</html> 

Output:

Old Heading

JavaScript changed “Old Heading” to “New Heading”.

Changing the Value of an Attribute

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

document.getElementById(id).attribute = new value

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

<!DOCTYPE html>
<html>
<body>

<img id="image" src="https://lenadesign.org/wp-content/uploads/2021/05/bike-animation.jpg" width="320" height="240" alt="cyclist">

<script>
document.getElementById("image").src = "https://lenadesign.org/wp-content/uploads/2020/02/css-doughnut.jpg";
</script>

</body>
</html>

Output:

cyclist

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 “bike-animation.jpg” to “dougnut.jpg”.

Enjoy coding!

Read also:

JavaScript HTML DOM

JavaScript Introduction

JavaScript Math Object