Introduction

Basically, DOM modification is the key to making pages dynamic.
  1. Creating elements
    • document.createElement(tag)
      Creates a new DOM element of type node:
      var div= document.createElement('div')
    • document.createTextNode(text)
      Creates a new DOM element of type text:
      var text = document.createTextNode('Abhijeet!!')
  2. Adding elements
    If we want to do something with an element then we need to call the corresponding method of its parent:
    • parentElem.appendChild(elem)
      Appends elem to the children of parentElem.
      1. <div>
      2. ...
      3. </div>
      4. <script>
      5. var abhi = document.body.children[0]
      6. var cam = document.createElement('cam')
      7. cam.innerHTML = 'hello world!'
      8. abhi.appendChild(cam)
      9. </script>
      The new node becomes the last child of the parentElem.
    • parentElem.insertBefore(elem, nextSibling)
      Inserts elem into the children of parentElem before the element nextSibling.
      Here is an example that inserts a new node before the first child:
      1. <div>
      2. ...
      3. </div>
      4. <script>
      5. var abhi = document.body.children[0]
      6. var cam = document.createElement('cam')
      7. cam.innerHTML = 'hello world!'
      8. abhi.insertBefore(cam, abhi.firstChild)
      9. </script>
  3. Removing nodes
    • parentElem.removeChild(elem)
      Remove elem from the children of parentElem.
    • parentElem.replaceChild(elem, currentElem)
      Replace the child element of parentElem, referenced by currentElem with the elem.