Computer >> Computer tutorials >  >> Programming >> Javascript

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 

  • afterbegin

  • afterend

  • beforebegin

  • beforeend

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

Example

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.

<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

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.

<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