HTML DOM insertAdjacentText( ) Method


The HTML DOM insertAdjacentText() method inserts text string at a specified position.

Syntax

Following is the syntax −

Calling insertAdjacentText() with parameters of positionString and text

node.insertAdjacentText(“positionString”, text)

Position Strings

Here, “positionString” can be the following −

positionStringDescription
afterbeginIt inserts text after the beginning of node element
afterendIt inserts text after the node element
beforebeginIt inserts text before the node element
beforeendIt inserts text before the end of node element

Example

Let us see an example for InsertAdjacentText() method −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>insertAdjacentText()</title>
<style>
   form {
      width:70%;
      margin: 0 auto;
      text-align: center;
   }
   * {
      padding: 2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius: 10px;
   }
</style>
</head>
<body>
<form>
<fieldset>
<legend>insertAdjacentText( )</legend>
<h1>First Muslim President of India</h1>
<h2 id="president">A.P.J Abdul Kalam</h2>
<input type="button" onclick="rectifyName()" value="Correct Name">
</fieldset>
</form>
<script>
   function rectifyName() {
      var presidentH2 = document.getElementById("president");
      presidentH2.insertAdjacentText("afterbegin", "DR. ");
   }
</script>
</body>
</html>

Output

This will produce the following output −

Before clicking ‘Correct Name’ button −

After clicking ‘Correct Name’ button −

Updated on: 30-Jul-2019

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements