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
Adding class name or id to Table with JS
提问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()
Use the same function to set class
, just like @Zakaria mentioned.
使用相同的函数来设置class
,就像@Zakaria 提到的那样。