How to use the innerHTML Attribute In Javascript
To add HTML code to a div using the ‘innerHTML
'
attribute in JavaScript, select the div and simply use +=
to append the new code.
Syntax:
element.innerHTML += "additional HTML code"
// OR
element.innerHTML = element.innerHTML +
"additional HTML code"
Example: This example uses the above-explained approach to append the HTML code to a div using JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>
How to Append HTML Code to
a Div using Javascript?
</title>
<style>
body {
text-align: center;
padding: 5%;
}
h1 {
color: green;
}
</style>
</head>
<body>
<div id="add_to_me">
<h1>w3wiki</h1>
<p>
This is the text which has
already been typed into
the div
</p>
</div>
<button onclick="addCode()">
Add Stuff
</button>
<script>
function addCode() {
document.getElementById("add_to_me")
.innerHTML +=
`<h3>
This is the text which has
been inserted by JS
</h3>`;
}
</script>
</body>
</html>
Output:
Note: This method basically destroys all the content of the div and recreates it. So, if you have any listeners attached to the child nodes of that div, they will be lost.
How to append HTML code to a div using JavaScript ?
Want to dynamically add new content to your web pages? JavaScript makes it easy to inject HTML code directly into specific “div” elements. In JavaScript, there are several ways to append HTML code to a div. To append an HTML code to a div, we will first select the div element by using the DOM selector methods, then we will use the below-mentioned methods to append the HTML code to the div.
There are two ways to append HTML code to a div through JavaScript:
Table of Content
- Using the innerHTML Attribute
- Using the insertAdjacentHTML() Method
- Using the appendChild() method