Introduction
Basically, DOM modification is the key to making pages dynamic.
- 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!!')
- document.createElement(tag)
- Adding elementsIf 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.The new node becomes the last child of the parentElem.
- <div>
- ...
- </div>
- <script>
- var abhi = document.body.children[0]
- var cam = document.createElement('cam')
- cam.innerHTML = 'hello world!'
- abhi.appendChild(cam)
- </script>
- 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:
- <div>
- ...
- </div>
- <script>
- var abhi = document.body.children[0]
- var cam = document.createElement('cam')
- cam.innerHTML = 'hello world!'
- abhi.insertBefore(cam, abhi.firstChild)
- </script>
- parentElem.appendChild(elem)
- 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.
- parentElem.removeChild(elem)

Comments
Join the conversation! Your thoughts help the community grow.