簡體   English   中英

JavaScript-創建dom元素並追加到正文

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM