Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
10
rated 0 times [  15] [ 5]  / answers: 1 / hits: 32956  / 9 Years ago, thu, november 12, 2015, 12:00:00

Suppose this code to create a 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);


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 :



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

More From » html

 Answers
15

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



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

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


Hope this helps.


[#64413] Tuesday, November 10, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jacquezf

Total Points: 27
Total Questions: 109
Total Answers: 98

Location: Lesotho
Member since Wed, Jun 2, 2021
3 Years ago
;