Javascript DOM HTML Element insertAdjacentHTML() Method with beforebegin as position

Introduction

Using the "beforebegin" value:

Click the button to insert a span before 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 span</button>

<script>
function myFunction() {//  w w w  .  j  a v  a 2 s  . c  om
  var h = document.getElementById("myH2");
  h.insertAdjacentHTML("beforebegin", "<span style='color:red'>My span</span>");
}
</script>

</body>
</html>



PreviousNext

Related