我有时需要向现有的HTML页面添加元素(例如新的链接和图像),但我只能访问远离我的页面的一小部分需要插入元素。我想使用基于DOM的JavaScript技术,并且我必须避免使用document.write()。使用JavaScript将新元素添加到DOM中(appendChild)
到目前为止,我一直在使用这样的事情:
// 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);
有,我可以用它来完成同样的事情更有效的方法?这一切似乎都是必要的,但我想知道是否有更好的方法可以做到这一点。
谢谢!我会检查一下我的下一个项目。 – KatieK 2010-06-03 16:50:13
+1因为John Resig。 – 2012-09-10 01:16:07