简体   繁体   English

JavaScript-创建dom元素并追加到正文

[英]javascript - create dom element and append to body

I'm trying to create a function generating dom element. 我正在尝试创建一个函数来生成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');

This tag didn't seem to be created because function dom output an error: 该标签似乎未创建,因为函数dom输出错误:

Uncaught TypeError: Cannot read property 'appendChild' of null all.js:438

How could I make it right? 我该怎么做呢? Thank you. 谢谢。

Where is all.js? all.js在哪里? If all.js was in head element, you need to run the code after onload or DOMContentLoaded. 如果all.js位于head元素中,则需要在onload或DOMContentLoaded之后运行代码。

// DOMContentLoaded or load
window.addEventListener("DOMContentLoaded", function(){
    dom('div',{class : 'test',id : 'test'},'hello world');
}, false);

Demo 演示版

class is a reserved tag, you can't use this as a key. class是保留标记,您不能将其用作键。 So, you have take another key for the class and check for it in the loop like this: 因此,您需要使用该类的另一个键,并在循环中进行如下检查:

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');

Furthermore, don't name you're element "tag", use a more describing name. 此外,不要将您的名字命名为“标签”,而应使用更具描述性的名称。

Here is a working example 这是一个有效的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM