New nodes

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 :-

  // creates a new element by the argumented tagname.
  var link = document.createElement('a');
It creates a link pointing to the page abc.php. We can insert it anywhere we wish.
To create a new SPAN we, use :-
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 :-

           <ol id='ol1'>
                <li id='li1'>
                       <span id='span1'>
                             This is Text 1
                  <li id='li2'>
                        <span id='span2'>
                              This is Text 2
                 <li id='li3'>
                        <span id='span3'>
                              This is Text 3

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[0].lastChild.firstChild
var object1 = document.getElementById("span3");
var txt = document.createTextNode(" This is newly created DIV.");

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 :-

Member Login

Member Login

Not a Member? Sign Up!

Login to comment

Be the first to comment on this topic


<<< Wanna review

Continue >>>