Insert element before another element in JavaScript

Description

The following code shows how to insert element before another element.

Example


<!--   w w  w  . j a va 2s. c om-->
<!DOCTYPE HTML>
<html>
<body>
<p id="textblock">
This is a test.
</p>
<p>
<button id="insert">Insert Element</button>
</p>
<script>
document.getElementById("insert").onclick = function() {
var textBlock = document.getElementById("textblock");
textBlock.firstChild.splitText(10);
var newText = textBlock.childNodes[1].splitText(4).previousSibling;
textBlock.insertBefore(document.createElement("b"), newText).appendChild(newText);
}
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Insert element before another element in JavaScript
Home »
  Javascript Tutorial »
    DOM »
      Insert
Javascript Tutorial Insert
Add child to a HTML element in JavaScript
Insert a node before another element using ...
Insert as the new first child in JavaScript
Insert before last child in JavaScript
Insert element before another element in Ja...
Insert to adjacent html with afterbegin in ...
Insert to adjacent html with afterend in Ja...
Insert to adjacent html with beforebegin in...
Insert to adjacent html with beforeend in J...