gpt4 book ai didi

javascript - 将 Nodelist 转换为 Array 并将新类附加到每个 Node

转载 作者:行者123 更新时间:2023-11-30 11:35:31 27 4
gpt4 key购买 nike

我浏览了大量有关从 NodeList 创建数组(在本例中为 document.getElementsByClassName() )的文章,以便迭代和修改 className每个节点上的属性...但是我无法完成任何类型的更改。看起来有点荒谬,但这是代码:

编辑:问题似乎与从 document.getElementsByClassName 创建数组有关。它创建的东西看起来像数组,但并不是真正的数组。请参阅下面的屏幕截图。

var cols = document.getElementsByClassName('cell symmetry');
[].forEach.call(cols, (node) => {
node.className += ' transiting';
console.log(node.className);
});

cols返回一个表格单元格数组。但是使用赋值运算符或尝试将另一个类附加到节点上没有任何作用。已尝试过document.querySelector 、 while 循环、for 循环、Array.prototype.slice.call... ,但没有骰子。

控制台截图:

enter image description here

最佳答案

演示中对详细信息进行了广泛评论

演示

/* 
|>.querySelectorAll()
|| Collect all .cell into a "static" NodeList

|>Array.from()
|| Convert NodeList into an array

|~.getElementsByClassName()
|| Does the same as .querySelectorAll({.class})
|| except that gEBCN() returns a "Live Collection"
|| which means that it changes in real time so
|| that there's a good chance you may end up with
|| half the expected length of the collection.
|| 99% of the time .qSA() is the better choice
|| because it returns a "static" NodeList.
*/
var cellArray = Array.from(document.querySelectorAll('.cell'));

/*
|>.forEach()
|| Iterate through array and invoke a function on
|| each node.
*/
cellArray.forEach(function(node, idx) {

/*
|>.classList.add()
|| Adds a class to a node's list of classes
*/
node.classList.add('transiting');
});
table {
width: 50%
}

.cell {
border: 1px solid blue;
background:blue;
}

.transiting {
border: 5px solid red;
}
<table>
<tr>
<td class='cell'>&nbsp;</td>
<td class='cell'>&nbsp;</td>
<td class='cell'>&nbsp;</td>
</tr>
<tr>
<td class='cell'>&nbsp;</td>
<td class='cell'>&nbsp;</td>
<td class='cell'>&nbsp;</td>
</tr>
<tr>
<td class='cell'>&nbsp;</td>
<td class='cell'>&nbsp;</td>
<td class='cell'>&nbsp;</td>
</tr>
<tr>
<td class='cell'>&nbsp;</td>
<td class='cell'>&nbsp;</td>
<td class='cell'>&nbsp;</td>
</tr>
</table>

关于javascript - 将 Nodelist 转换为 Array 并将新类附加到每个 Node,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44641918/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com