Javascript DOM HTML Element insertAdjacentText() Method

Introduction

Insert text after the specified header element:

Click the button to insert some text after the header:

View in separate window

<!DOCTYPE html>
<html>
<body>
<p>This method inserts a specified text, into a specified position.</p>

<h2 id="myH2">My Header</h2>
<button onclick="myFunction()">Insert text</button>

<script>
function myFunction() {/*from   w  w w.  ja v a2 s  .  co  m*/
  var h = document.getElementById("myH2");
  h.insertAdjacentText("afterend", "My inserted text");
}
</script>

</body>
</html>

The insertAdjacentText() method inserts a the specified element into a specified position.

Legal position values are:

  • "afterbegin"
  • "afterend"
  • "beforebegin"
  • "beforeend"
insertAdjacentText(position, text);

Parameter Values

Parameter
Type
Description
position






String






Required.
A position relative to the element.
Legal values:
"afterbegin" - After the beginning of the element as the first child
"afterend" - After the element
"beforebegin" - Before the element
"beforeend" - Before the end of the element as the last child
text
String
The text you want to insert



PreviousNext

Related