Javascript DOM HTML Element insertAdjacentElement() Method beforebegin

Introduction

Using the "beforebegin" value:

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

View in separate window

<!DOCTYPE html>
<html>
<body>
<p>This method inserts a specified element, into a specified position.</p>
<h2 id="myH2">My Header</h2>

<span style="color:red">My span</span>
<button onclick="myFunction()">Move span</button>

<script>
function myFunction() {/*  ww  w .  j a v a2 s  .  c  o  m*/
  var s = document.getElementsByTagName("span")[0];
  var h = document.getElementById("myH2");
  h.insertAdjacentElement("beforebegin", s);
}
</script>

</body>
</html>



PreviousNext

Related