javascript - 获取错误 "' getAttribute' of undefined "for the last element in the loop

标签 javascript html loops

不明白为什么循环中的最后一个元素会出现错误?我在 SOF 上看到其他问题,但没有找到适合我的案例的答案。

我正在尝试获取 tag a 元素的列表,但是

<script>

    let a = document.body.getElementsByTagName('a');

    function getList(list) {

        let ii;
        for (let i = 0; i , a.length; i++) {

            if (a[i].getAttribute('href')) {
                ii = a[i].getAttribute('href');
                console.log(ii); // get the list of elements that contains attr "href". 
                                 // and an Error for the last element -
                                 // error 'getAttribute' of undefined.
            }
        }

        return ii;
    }

    getList(); // start for test

</script>


<body>
    <ul>
      <li><a href="http://google.com">http://google.com</a></li>
      <li><a href="/tutorial">/tutorial.html</a></li>
      <li><a href="local/path">local/path</a></li>
    </ul>
</body>

最佳答案

你应该把条件 < ;

for (let i = 0; i < a.length; i++)

关于javascript - 获取错误 "' getAttribute' of undefined "for the last element in the loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48321254/

相关文章:

javascript - AngularJs 服务方法接受对象或多个参数 - 哪一个是最佳实践

javascript - ng-model 导致 AngularJS 输出中的计算失败

Javascript:将动态生成的值分配给新数组

r - 从矩阵列表创建 X % 概率矩阵

php - 无法链接到上一层的 index.html

c# - C# 中的 ForEach 循环问题

javascript - 是否可以在 html 文本字段中显示图像?

javascript - 为什么 ~N 在 JavaScript 中执行 -(N + 1)?

javascript - 限制相机在 Y 轴上的旋转

javascript - 根据一天中的时间更改颜色