摘要: 在本教程中,您将学习如何使用 forEach()
方法和 for 循环遍历选定的元素。
使用 querySelectorAll()
或 getElementsByTagName()
选择元素后,您将获得一个作为 NodeList
的元素集合。
要遍历选定的元素,您可以使用 forEach() 方法(大多数现代 Web 浏览器支持,IE 除外)或直接使用普通的 for 循环。
使用 forEach() 方法
以下代码选择所有 CSS 类为 .note 的元素,并将背景颜色更改为黄色
const notes = document.querySelectorAll('.note');
notes.forEach((note) => {
note.style.backgroundColor = 'yellow';
});
Code language: JavaScript (javascript)
或者,您可以 借用 forEach() 方法 Array 对象,如下所示
[].forEach.call(notes, (note) => {
note.style.backgroundColor = "yellow";
});
Code language: PHP (php)
使用 for 循环
以下代码使用 for 循环遍历选定的元素
const notes = document.querySelectorAll('.note');
const count = notes.length;
for (let i = 0; i < count; i++) {
notes[i].style.backgroundColor = "yellow";
}
Code language: JavaScript (javascript)
本教程对您有帮助吗?