How to use the insertAdjacentHTML() Method In Javascript
HTML code can be appended to a div element using the insertAdjacentHTML() method. You need to pass the content after which the HTML code needs to be append inside the div tag and the code that need to be inserted.
Syntax:
elementInsideDiv.insertAdjacentHTML(
'afterend',
'additional HTML code'
);
Example: The below code example implements the insertAdjacent() method to append HTML in a div.
<!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 id="add_after_me">
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_after_me")
.insertAdjacentHTML("afterend",
`<h3>
This is the text which has
been inserted by JS
</h3>`);
}
</script>
</body>
</html>
Output:
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
Contact Us