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!!')
- 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.
- <div>
- ...
- </div>
- <script>
- var abhi = document.body.children[0]
- var cam = document.createElement('cam')
- cam.innerHTML = 'hello world!'
- abhi.appendChild(cam)
- </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:
- <div>
- ...
- </div>
- <script>
- var abhi = document.body.children[0]
- var cam = document.createElement('cam')
- cam.innerHTML = 'hello world!'
- abhi.insertBefore(cam, abhi.firstChild)
- </script>
- 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.