我有時需要向現有的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