Javascript document.createElement



Javascriptdocument.createElement creates a new tag in the document. To give the new tag attributes, we use its setAttribute() method. For example, to create a node containing an "A" tag and then append the HREF attribute to it, we use the following:

var link = document.createElement('a');
link.setAttribute('href', 'http://server/jquery.html');

The above example would create a link pointing to "http://server/jquery.html" (<A HREF="http://server/jquery.html"/>).

You can add inner text Go! to the above attribute as follows:

link.innerText ="Go!";

Above jquery code has now made complete HREF as: <A HREF="http://server/jquery.html">Go!</a>

Now, this needs to be added to the page somewhere. This we do by fetching some DIV (here myDivLink) and then appending above created html element to it as follows:

var spanAppend = document.getElementById('myDivLink');
spanAppend.appendChild(link);