Cyber Week

Save big!

All courses under $5 - for a limited time!

Code has been added to clipboard!

Learn JavaScript InnerHTML: HTML in JavaScript Explained

Reading time 2 min
Published Aug 8, 2017
Updated Oct 15, 2019

Understanding how you can perform DOM manipulation using JavaScript with options like JavaScript innerHTML allows you to add handy features to your website.

In this tutorial, you will learn how you can change HTML using JavaScript, and read about the most popular ways of adjusting HTML content through the use of JavaScript. That includes JavaScript innerHTML property, which allows you to change the content of any text tag according to your needs.

JavaScript innerHTML: Main Tips

  • To allow JavaScript to change the content of an HTML element, we use HTML DOM.
  • JavaScript can be used to create HTML content that is dynamic.

Changing HTML

In JavaScript, document.write() is the first DOM manipulation function. It's only logical we start our tutorial with it, right? Using this command, you can write directly to the HTML output stream.

Example
document.write(Date());

This JavaScript write HTML method is commonly applied for testing. When using it for different purposes, a warning should be taken into account: you should always execute document.write() when the document is already loaded - otherwise, an overwrite will occur.

Using innerHTML to Modify Content

The easiest way of editing content in an HTML element is to use the innerHTML property.

In the code example below, we're using the JavaScript innerHTML property to change the content of the element <p>:

Example
document.getElementById("p2").innerHTML = "Hello World again!";

Now, in the code example below, we change the content of the element <h1>:

Example
var element = document.getElementById("id1");
element.innerHTML = "New heading";

Altering Attribute Value

You can also change the values of HTML attributes.

Take a look at the example below. In it, we change the value of the src attribute for the <img> element:

Example
document.getElementById("myImage").src = "background.jpg";

JavaScript innerHTML: Summary

  • You can use JavaScript innerHTML property to change the content in the HTML.
  • You can learn more about JavaScript innerHTML in this tutorial.
  • You can use JavaScript to change the values of HTML element's attributes as well.