不明白为什么循环中的最后一个元素会出现错误?我在 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/