insertBefore

In this chapter you will learn:

  1. How to insert element before another element

Insert before

The following code inserts an Element into a Text Block.

<!DOCTYPE HTML> <!--from   j  ava 2 s . c om-->
<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

Next chapter...

What you will learn in the next chapter:

  1. How to compare the results from two different queries
  2. How to compare two table rows
Home » Javascript Tutorial » HTML Operation
HTMLElement
addEventListener
appendChild
attributes
classList
className
cloneNode
createElement
createTextNode
dataset
getAttribute
getElementsByTagName
hasAttribute
innerHTML
insertAdjacentHTML
insertBefore
isSameNode
outerHTML
onmouseout
onmouseover
removeEventListener