Skip to main content

Using innerHTML in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to use the innerHTML property in JavaScript to access and manipulate the HTML content of a given HTML element in the DOM. We'll cover the basics of the innerHTML property and provide sample code with explanations.

What is innerHTML?

The innerHTML property is a built-in JavaScript DOM property that allows you to access and manipulate the HTML content of a given HTML element. The innerHTML property returns a string containing the HTML content of the element, and you can also set the HTML content of an element by assigning a new value to the innerHTML property.

Sample Code: Using innerHTML

Let's say we have the following HTML document:

<!DOCTYPE html>
<html>
<head>
<title>innerHTML Example</title>
</head>
<body>
<div id="mainContainer">
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
</div>
</body>
</html>

To use innerHTML to access and manipulate the HTML content of an element, you'll need to include a JavaScript <script> tag in your HTML document. For this example, we will add an inline script, although it's generally recommended to use external JavaScript files for larger projects.

Here's how you can access the HTML content of the div element with the ID mainContainer and change its content:

<!DOCTYPE html>
<html>
<head>
<title>innerHTML Example</title>
</head>
<body>
<div id="mainContainer">
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
</div>

<script>
// Select the element with the ID "mainContainer"
var mainContainer = document.getElementById('mainContainer');

// Access its inner HTML content
console.log('Original content:', mainContainer.innerHTML);

// Modify the inner HTML content
mainContainer.innerHTML = '<h2>New Content</h2><p>This content was added using innerHTML.</p>';

// Verify the changes
console.log('Updated content:', mainContainer.innerHTML);
</script>
</body>
</html>

After running this code, the content inside the div element with the ID mainContainer will be replaced with the new content specified in the innerHTML property.

Live Playground, Try it Yourself

Conclusion

The innerHTML property is a useful tool for accessing and manipulating the HTML content of a given HTML element in the DOM. By mastering this property, you can easily change the content of your web pages dynamically, allowing you to create interactive and engaging web experiences.