Javascript DOM HTML Element insertAdjacentElement() Method

Introduction

Move a span element to after the header element:

Click the button to insert the red span after the header:

View in separate window

<!DOCTYPE html>
<html>
<body>

<p>This method inserts a specified element, into a specified position.</p>

<span style="color:red">My span</span>

<h2 id="myH2">My Header</h2>
<button onclick="myFunction()">Move span</button>

<script>
function myFunction() {//from  w  w w  .ja  va 2s  .c o m
  var s = document.getElementsByTagName("span")[0];
  var h = document.getElementById("myH2");
  h.insertAdjacentElement("afterend", s);
}
</script>

</body>
</html>

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

Legal position values are:

"afterbegin"
"afterend"
"beforebegin"
"beforeend"
insertAdjacentElement(position, element);

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
element
HTML Element
The element you want to insert



PreviousNext

Related