Javascript 使用 JS 将类名或 id 添加到表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33682483/
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-23 15:20:24  来源:igfitidea点击:

Adding class name or id to Table with JS

javascripthtmldomsetattribute

提问by user1170330

Suppose this code to create a table with plainJavaScript using DOM (Fiddle):

假设此代码使用 DOM ( Fiddle)使用JavaScript创建一个表:

var table = document.createElement('table');
for (var i = 1; i < 4; i++){
    var tr = document.createElement('tr');   

    var td1 = document.createElement('td');
    var td2 = document.createElement('td');

    var text1 = document.createTextNode('Text1');
    var text2 = document.createTextNode('Text2');

    td1.appendChild(text1);
    td2.appendChild(text2);
    tr.appendChild(td1);
    tr.appendChild(td2);

    table.appendChild(tr);
}
document.body.appendChild(table);

How can I add a class name or an id to its cells?
For example I want to be able to modify cells after their creation, so I want just :

如何在其单元格中添加类名或 id?
例如,我希望能够在创建后修改单元格,所以我只想:

table.getElementsByClassName("class").style.font-weight: "bold"; 

回答by Zakaria Acharki

Use HTML DOM setAttribute() Methodto add attributes to an element, like following :

使用HTML DOM setAttribute() 方法为元素添加属性,如下所示:

var td1 = document.createElement('td');
var td2 = document.createElement('td');

td1.setAttribute('class', 'className');
td2.setAttribute('class', 'className');

Hope this helps.

希望这可以帮助。

回答by Rahul Desai

Do:

做:

table.setAttribute("id", "myId");

Read up: MDN Element.setAttribute()

阅读:MDNElement.setAttribute()

Use the same function to set class, just like @Zakaria mentioned.

使用相同的函数来设置class,就像@Zakaria 提到的那样。