小编suy*_*til的帖子

为什么 forEach 方法不适用于 HTMLCollection

我正在学习 DOM 操作并有一个 HTML 文档。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1 class="test">
        Title
    </h1>
    <h2 class="test">
        Here is the list of all the programming languages:
    </h2>
    <ul>
        <li>JavaScript</li>
        <li>Python</li>
        <li>Go</li>
    </ul>
    <script>
        const test = document.getElementsByClassName('test');
        test.forEach(item => {
            console.log(item);
        });
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我尝试使用 forEach 方法访问 html 元素,但它给出错误,指出 test.forEach 不是函数。

html javascript dom

0
推荐指数
1
解决办法
267
查看次数

标签 统计

dom ×1

html ×1

javascript ×1