[英]javascript - create dom element and append to body
我正在嘗試創建一個函數來生成dom元素。
function dom(tag,attr,inner){
var tag = document.createElement(tag);
for (var key in attr) {
if (attr.hasOwnProperty(key)) {
tag.setAttribute(key,attr[key]);
}
}
tag.innerHTML = inner;
document.body.appendChild(tag);
}
dom('div',{class : 'test',id : 'test'},'hello world');
該標簽似乎未創建,因為函數dom
輸出錯誤:
Uncaught TypeError: Cannot read property 'appendChild' of null all.js:438
我該怎么做呢? 謝謝。
all.js在哪里? 如果all.js位於head元素中,則需要在onload或DOMContentLoaded之后運行代碼。
// DOMContentLoaded or load
window.addEventListener("DOMContentLoaded", function(){
dom('div',{class : 'test',id : 'test'},'hello world');
}, false);
class
是保留標記,您不能將其用作鍵。 因此,您需要使用該類的另一個鍵,並在循環中進行如下檢查:
function dom(tag,attr,inner){
var el = document.createElement(tag);
for (var key in attr) {
if (attr.hasOwnProperty(key)) {
el.setAttribute(key,attr[key]);
}
if (key=="OtherIdentifierForClass"){
el.setAttribute("class",attr[key]);
}
}
el.innerHTML = inner;
document.body.appendChild(el);
}
dom('div',{OtherIdentifierForClass : 'test',id : 'test'},'hello world');
此外,不要將您的名字命名為“標簽”,而應使用更具描述性的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.