In this tutorial we will see how to Insert HTML Code anywhere With JavaScript. We have used insertAdjacentHTML Method for this, using which we can add HTML content before or after or even inside any HTML tag.
Table of Contents
HTML Code
HTML Code is given below, This code contains two paragraph tags with dummy text in them. Each p tag has it's own unique id.
<!DOCTYPE html>
<html>
<head>
<title>Insert HTML Code anywhere With JavaScript</title>
</head>
<body>
<p id="one">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
<p id="two">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, this code is further explained below.
<script>
var ref =document.getElementById('two');
var htmlCode = '<div><h1>Heading</h1><p>Paragraph</p></div>';
ref.insertAdjacentHTML('afterend',htmlCode);
</script>
Demo
getElementById() Method
getElementById() method is used to target or select the HTML element. In this example it is used to select the HTML element after which or before which, we can add HTML content.
insertAdjacentHTML Method
The insertAdjacentHTML inserts HTML Content at a specified position, The predefined positions that we can use are beforeend, afterend, beforebegin and afterbegin.
This JavaScript insertAdjacentHTML Method is used in this example as well to insert HTML Content anywhere in the page.
In above JavaScript code we have used afterend, which is used to insert or add HTML content after particular tag or element.
We can also use beforebegin to add same HTML content before that particular HTML tag.
Video Tutorial
Watch video tutorial on how to Insert HTML Code anywhere With JavaScript.