使用 JS 添加 class name 或 id 到 Table

Adding class name or id to Table with JS

假设此代码创建一个 table with plain JavaScript using DOM (Fiddle):

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

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

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

使用HTML DOM setAttribute() Method向元素添加属性,如下所示:

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

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

希望对您有所帮助。

做:

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

阅读:MDN Element.setAttribute()

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