Javascript DOM HTML Element insertAdjacentHTML() Method

Introduction

Insert a new <p> element after the header element:

Click the button to insert a paragraph after the header:

View in separate window

<!DOCTYPE html>
<html>
<body>
<p>This method inserts a specified text as HTML, into a specified position in the document.</p>

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

<script>
function myFunction() {//from www  .jav  a  2 s  .  c  o  m
  var h = document.getElementById("myH2");
  h.insertAdjacentHTML("afterend", "<p>My new paragraph</p>");
}
</script>

</body>
</html>

The insertAdjacentHTML() method inserts a text as HTML, into a specified position.

Legal position values are:

  • "afterbegin"
  • "afterend"
  • "beforebegin"
  • "beforeend"
insertAdjacentHTML(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