Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new elements into DOM using JavaScript (appendChild)

Tags:

javascript

dom

I sometimes need to add elements (such as a new link and image) to an existing HTML page, but I only have access to a small portion of the page far from where I need to insert elements. I want to use DOM based JavaScript techniques, and I must avoid using document.write().

Thus far, I've been using something like this:

//  Create new image element
var newImg = document.createElement("img");
  newImg.src = "images/button.jpg";
  newImg.height = "50";
  newImg.width = "150";
  newImg.alt = "Click Me";
//  Create new link element
var newLink = document.createElement("a");
  newLink.href = "/dir/signup.html";
//  Append new image into new link
newLink.appendChild(newImg);
//  Append new link (with image) into its destination on the page
document.getElementById("newLinkDestination").appendChild(newLink);

Is there a more efficient way that I could use to accomplish the same thing? It all seems necessary, but I'd like to know if there's a better way I could be doing this.

like image 752
KatieK Avatar asked Jun 02 '10 22:06

KatieK


2 Answers

There is a more efficient way, and seems to be using documentFragments if possible. Check it out: http://ejohn.org/blog/dom-documentfragments/ . Also this way should be less error prone and more maintainable than starting to mix up huge strings literals and setting them as innerHTML of some other DOM objects.

like image 129
mati Avatar answered Oct 10 '22 13:10

mati


Just beware, that innerHTML is both non-standard and notoriously buggy.

like image 33
dplass Avatar answered Oct 10 '22 13:10

dplass