Categories
JavaScript Web development

JavaScript HTML DOM/HTML

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

JavaScript HTML DOM/HTML
Do you like this gif? Check more gifs in the store.

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>

<h2>JavaScript can Change HTML</h2>

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

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

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

</body>
</html>

Output:

Example explained:

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

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

<!DOCTYPE html>
<html>
<body>

<h1 id="id01">Old Heading</h1>

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

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

</body>
</html> 

Output:

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="smiley.gif" width="160" height="120">

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

<p>The original image was smiley.gif, but the script changed it to landscape.jpg</p>

</body>
</html>

Output:

Example explained:

The HTML document above contains an <img> element with id=”myImage”. We use the HTML DOM to get the element with id=”myImage”. A JavaScript changes the src attribute of that element from “smiley.gif” to “landscape.jpg”.

Enjoy coding!

Leave a Reply