.insertBefore()

An alternative approach to the appendChild() method is to use the .insertBefore() method, as follows:

 

  1. Create the new element, using the .createElement() method
  2. Create a handle to the required insertion point
  3. Use the .insertBefore() method to insert the new element (from 1) before the handle (from 2)

 

Taking the above we therefore have:

 

var newElem = document.createElement("li") ;

var sixthLi = myExisting.getElementsByTagName("li")[5] ;

myExisting.insertBefore(newElem, sixthLi) ;

 

 

This example shows an ordered list of ten items, using the .insertBefore method to insert a new element before the sixth list item:

Save & refresh browser:

  1. First list item
  2. Second list item
  3. Third list item
  4. Fourth list item
  5. Fifth list item
  6. THIS IS THE NEWLY INSERTED LIST ITEM
  7. Sixth list item
  8. Seventh list item
  9. Eighth list item
  10. Ninth list item
  11. Tenth list item

 

 


.insertAfter()

 

Although there its no insert after method, a function can be created to simulate this as follows:

Save & refresh browser:

  1. First list item
  2. Second list item
  3. Third list item
  4. Fourth list item
  5. Fifth list item
  6. Sixth list item
  7. THIS IS THE NEWLY INSERTED LIST ITEM
  8. Seventh list item
  9. Eighth list item
  10. Ninth list item
  11. Tenth list item

Leave a Reply