[英]Cannot style elements using DOM manipulation when new class is added by element.classList.add() method in javascript
I am trying to style a table like this我正在尝试设计这样的表格
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td >Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td >Jackson</td>
<td>94</td>
</tr>
</table>
which has a Javascript code that would create classes shown below它有一个 Javascript 代码,可以创建如下所示的类
td.classList.add("col");
However I don't understand why styling using that class won't work with the below code但是我不明白为什么使用该 class 的样式不适用于以下代码
const tabl= document.getElementsByClassName("col");
for (var i = 0; i < tabl.length; i++) {
tabl[i].style.backgroundColor="red";
}
Why use class name?为什么使用 class 名称? Please try this.
请试试这个。 Hope it can help
希望它可以帮助
var elements = document.getElementsByTagName('td') var tds = Array.from(elements) tds.map(element => { element.setAttribute('class', 'classname') }) // check console.log('finded tds: ' + document.getElementsByClassName('classname').length)
<table> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td >Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td >Jackson</td> <td>94</td> </tr> </table>
So, I can't see where you're going wrong from the little code you presented.因此,从您提供的小代码中,我看不出您哪里出错了。 I filled in the gaps as best I could to get this working, and it adds the red color for me.
我尽我所能填补了空白以使其正常工作,它为我添加了红色。
//Get NodeList of all tds
let tds = document.querySelectorAll('td');
//Convert NodeList to Array
tds = Array.from(tds);
//Add class 'col' to each td
tds.map((td) => td.classList.add('col'));
//Get all '.col' elements
const tabl= document.getElementsByClassName("col");
//Programmatically set style attribute on each .col
for (var i = 0; i < tabl.length; i++) {
tabl[i].style.backgroundColor="red";
}
It's generally considered bad practice to directly, programmatically set the style of an element in this way;以这种方式直接以编程方式设置元素的样式通常被认为是不好的做法; it's better to add a class and handle style via the CSS file.
最好通过 CSS 文件添加 class 和手柄样式。 Since you're already adding a class, why not just set that class to set background-color: red in the CSS file anyway?
既然您已经添加了 class,为什么不在 CSS 文件中将 class 设置为 background-color: red 呢?
Anyway, you can check a StackBlitz here to see it up and running: https://stackblitz.com/edit/js-2zm68n无论如何,您可以在此处查看 StackBlitz 以查看它的运行情况: https://stackblitz.com/edit/js-2zm68n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.