无法访问动态创建表中的类

无法访问动态创建表中的类

问题描述:

我已经使用js创建了一个表。我为几个单元格给出了类名。我想稍后访问这些单元并删除类名。但我无法做到。这是我如何创建动态表:无法访问动态创建表中的类

for (var j = 0; j < TotalNumOfPlayers; j++) 
{ 
    // Create a <td> element and a text node, make the text 
    // node the contents of the <td>, and put the <td> at 
    // the end of the table row 
    var cell = document.createElement("td"); 
    if (header) 
    { 
    var cellText = document.createTextNode(nameOfPlayers[j]); 
    } 
    else 
    { 
    var cellText = document.createTextNode(oldScore[j]);  
    cell.setAttribute("class", "lastrow"); 
    } 
    cell.appendChild(cellText); 
    row.appendChild(cell); 
} 

这里是我试图访问细胞,去除类:

document.querySelectorAll(".lastrow").classList.remove("lastrow"); 

它引发以下错误:

Cannot read property 'remove' of undefined at :1:48

我隐约明白,它正在看父母的层面,并没有看到任何班级,但应该看看td。我是否正确?如果是的话,我该如何做到这一点?

+1

喜* querySelectorAll *返回一个数组,你必须在这之后把指数与您选择的代码看起来像querySelectorAll(“ LASTROW”)[0] –

+0

改为'cell.setAttribute(“class”,“lastrow”);'最好使用'cell.classList.add('lastrow')' –

+0

哇..谢谢穆罕默德。这解决了它。 –

你应该从所有元素删除类环路

let lastrows = document.querySelectorAll('.lastrow'); 
for (let i=lastrows.length;i--;){ 
    lastrows[i].classList.remove('lastrow'); 
}