Html 从 createElement 方法向对象添加 ID/类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18648500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:05:29  来源:igfitidea点击:

Add ID/class to objects from createElement method

htmlcss

提问by Mika H.

This w3schools pagementions the HTML DOM createElement() Method. For example, you can create a button by

这个w3schools 页面提到了 HTML DOM createElement() 方法。例如,您可以通过以下方式创建按钮

var btn=document.createElement("BUTTON");

var btn=document.createElement("BUTTON");

However, how can I add ID/class to this button? And what else can I do with it?

但是,如何向此按钮添加 ID/类?我还能用它做什么?

回答by Patrick

One way with Javascript, is by using setAttribute:

Javascript 的一种方法是使用 setAttribute:

element.setAttribute(name, value);  

Example:

例子:

var btn=document.createElement("BUTTON");
btn.setAttribute("id", "btn_id");
btn.setAttribute("class", "btn_class");
btn.setAttribute("width", "250px");
btn.setAttribute("data-comma-delimited-array", "one,two,three,four");
btn.setAttribute("anything-random", document.getElementsByTagName("img").length);

The advantage of this way is that you can assign arbitrary values to arbitrary names. https://developer.mozilla.org/en-US/docs/Web/API/element.setAttribute

这种方式的优点是您可以为任意名称分配任意值。 https://developer.mozilla.org/en-US/docs/Web/API/element.setAttribute

回答by xdazz

You could assign to its property:

您可以分配给它的属性:

var btn=document.createElement("BUTTON");
btn.id = 'btn_id';
btn.className = 'btn_class';