使用JavaScript添加新元素到DOM(appendChild)

问题描述:

我有时需要向现有的HTML页面添加元素(如新的链接和图像),但我只能访问页面的一小部分,远离我需要插入元素的位置。我想使用基于DOM的JavaScript技术,我必须避免使用document.write()。

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.

有一种更有效的方式,如果可能,似乎使用documentFragments。
查看: http://ejohn.org/blog/dom-documentfragments/。此外,这种方式应该比开始混合大量字符串文字并将其设置为一些其他DOM对象的innerHTML时更容易出错,更易于维护。

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.