如何将CSS应用于字符串变量

时间:2019-01-09 19:52:34

标签: javascript html css

我有一个CSS类.table1,我需要将其应用到我在JavaScript中创建的字符串中。是否有任何特定元素可以帮助我添加它?

我尝试过setAttribute,但结果未定义

Settings.Sources

我需要将(.table1)应用于字符串c,但我没有弄清楚。  任何建设性的评论或答案将不胜感激。

2 个答案:

答案 0 :(得分:0)

除了其他人在注释中提出的建议之外,另一个选择是使用document.createElement()appendChild来重新创建表。然后,您可以按照自己的意愿执行setAttribute。使用它会像这样。

let table = document.createElement('table');
table.setAttribute('class', 'table1');
let firstRow = document.createElement('tr');
let firstElement = document.createElement('td');
firstElement.textContent = '1';
firstRow.appendChild(firstElement);
table.appendChild(firstRow);
....

等等,依此类推。显然,这可以简化并通过循环使其更短,但这是另一种方法。

答案 1 :(得分:0)

document.write("<style>.table1 { background-color:cyan; color:red; }</style>");