Javascript document.createElement

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


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);





Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.