Using the innerHTML property

You can use the DOM’s innerHTML property to access or change the contents of an HTML element in your app. You can then use the contents of the HTML element as a value in your JavaScript code.

var showList = document.getElementById("list");
alert(showList.innerHTML);

Here we have created a variable where the value is set to the contents of the HTML element that we have called “list“, using the id attribute.

We have then created an alert. The alert will pop up the value of our variable.

Our browser can access this information because we have set the innerHTML property of the variable.

The DOM is case sensitive. Make sure your capital letters are in the right place.

Let’s have a look at using the getElementById method with the innerHTML property to pop up an alert:

<!DOCTYPE html>
<html>
<head>
 <title>List Alert</title>
</head>
<body>
 <div id="list">Buy milk</div>
 <script>
 var showList = document.getElementById("list");
 alert(showList.innerHTML);
 </script>
</body>
</html>

In this example, we’ve used the getElementById method to find the < div > with the id attribute set to “list“.

You will remember < div > tags from earlier. They are containers for pieces of content and you can use them to divide your page into sections.

We’ve then stored the contents of that < div > in a variable.

Then we’ve used innerHTML to set the text in our alert to the value of our variable. If the text in the < div > changes, so will the text inside the alert box, without us having to write any more code.

METHODS AND PROPERTIES

1) Open up your text-editing program. Create a new HTML file called methods.html. In your < body > use the < input/ > tag to create a button. Also create an empty < div >, like this:

<!DOCTYPE html>
<html>
<head>
 <title>Methods</title>
</head>
<body>
 <input type="button" value="Add item"/>
 <div id="container"></div>
</body>
</html>

2) Now create a JavaScript function in your < head > that uses the getElementById method to find your empty < div >. Then use innerHTML to set the contents of your empty < div > to some text, like this:

<script>
 function addItem() {
 document.getElementById("container").innerHTML = "Item to remember";
 }
</script>

3) Then make your button call your JavaScript function when it is clicked. Add the onclick attribute to your < input/ > tag and set the value of the onclick attribute to the name of your function, like this:

<input type="button" value="Add item" onclick="addItem();"/>
<div id="container"></div>

4) Save your HTML file and open it in your browser. You will see a button. When you or user clicks on the button, the innerHTML text will be added to your tag  < div >.