Generating new nodes
We can generate a new node simply by writing a line of code, we just need to pass the specific tagname which needs to be generate. Following example will explain :-
document.createElement(tagname) // creates a new element by the argumented tagname. var link = document.createElement('a'); link.setAttribute('href','abc.php')It creates a link pointing to the page abc.php. We can insert it anywhere we wish.
To create a new SPAN we, use :-
document.createElement("SPAN")TO create a text node , we need to pass the text contents that we need to put in the newly defined node.
document.createTextNode("This is the text passed.")
Inserting nodes in document
Once the node you wish to add has been created, you must locate where you wish to append it in the document tree. The document tree is the representation of all tags, attributes, and text (all nodes) in the Document Object Model. To locate the place in the document tree we wish to append our new node to, we have a choice. You may either assign an ID to the place in the document you wish the new node to be inserted, or navigate the document tree by use of children and parents. This will be discussed later. To use an ID to locate where we wish to append our new node we use document.getElementById(). This will return the object (whether it be a DIV, P, SPAN, etc..) with the given ID. For instance, to access the DIV with the ID "myDiv", we would use:
We can instead insert the node by using the heirarchy of the document. For this we need to reach the particular part of the document using child and parents as discussed earlier. Lets explain through an example :-
<body> <ol id='ol1'> <li id='li1'> <span id='span1'> This is Text 1 </span> </li> <li id='li2'> <span id='span2'> This is Text 2 </span> </li> <li id='li3'> <span id='span3'> This is Text 3 </span> </li> </ol> </body>
First , we will go to span3 without using its ID. It can be accessed as :-
By, using its ID it can be easily be reached as discussed a number of times
Once , we have reached to the span3 thorugh either of the two ways available, we can insert it there in the following ways :-
var object1 = document.childNodes.lastChild.firstChild OR var object1 = document.getElementById("span3"); var txt = document.createTextNode(" This is newly created DIV."); object1.appendChild(txt);
The method mentioned above will simply append the code to the end of the div. However , if we wish to insert some contents at the beginning of the div, we can do so by declaring the inserted node as the first child of the div. This can be done in the following way :-
This will make a text node at the beginning of the div.
Lets learn to remove and replace child node of an element now :-