How to insert element before another element in Javascript

Insert before

The following code inserts an Element into a Text Block.

Example


<!DOCTYPE HTML> 
<html> 
<body> 
  <p id="textblock">
      This is a test. <!-- w ww .  j  a  v  a2  s.c  o  m-->
  </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





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window