如果我要做很多节点创建,我通常会为它编写一个函数,这样我就不必重复自己了。
// String, Object, String
function createElement(tagName, attribs, text) {
var elm = document.createElement(tagName), a;
if (attribs) // if given
for (a in attribs) // for each property
if (attribs.hasOwnProperty(a)) // that is not inherited
elm.setAttribute(a, attribs[a]); // set attribute
if (text) // if given
elm.appendChild(document.createTextNode(text)); // append text
return elm; // node out
}
现在容易多了;
// create the elements
var span = createElement('span', {'class': 'ABC'}),
img = createElement('img', {'src': 'http://www.google.com/favicon.ico'});
span.appendChild(img); // put image in span
document.getElementById('text').appendChild(span); // append wherever