Insert a specified HTML text into a specified position in the JavaScript document?


Javascript has provided insertAdjacentHTML() method to insert a text as HTML, into a specified position. Those legal positions are 

1) afterbegin

2) afterend

3) beforebegin

4) beforeend

Each legal position has its own unique importance. Let's discuss some of them.

Example-1

In the following example, using "insertAdjacentHTML()" method and a legal position "afterend", a new text is placed adjacent to the header and the result is displayed in the output.

Live Demo

<html>
<body>
<h2 id="H2">Header</h2>
<script>
   var ins = document.getElementById("H2");
   ins.insertAdjacentHTML("afterend","<p>Tutorix is the best e-learning platform</p>");
</script>
</body>
</html>

Output

Header

Tutorix is the best e-learning platform


Example-2

In the following example, using "insertAdjacentHTML()" method and a legal position "beforeend", a new text is placed adjacent to the header and the result is displayed in the output.

Live Demo

<html>
<body>
<h2 id="H2">Header</h2>
<script>
   var ins = document.getElementById("H2");
   ins.insertAdjacentHTML("beforeend","<p>Tutorix is the best e-learning platform</p>");
</script>
</body>
</html>

Output

Header

Tutorix is the best e-learning platform

raja
Published on 09-Aug-2019 11:32:30
Advertisements