Reputation: 1591
Here is my JavaScript code:
var all_videos = document.querySelectorAll(".video-feed-item-wrapper");
var all_urls = [];
console.log(all_videos.length);
for(i = 0; i <= all_videos.length; i++) {
all_urls.push(all_videos[i].getAttribute('href'));
}
console.log(all_urls);
It gives me the error all_videos[i]
is undefined. Why is it undefined?
Thanks.
Upvotes: 0
Views: 37
Reputation: 50346
Two issues here , first i
becomes a global variable and instead i <= all_videos.length
use only i < all_videos.length
. It is undefined
because i
trying the access the element which is not available. The element is not available because index
starts from 0
for(i = 0; i < all_videos.length; i++) {
all_urls.push(all_videos[i].getAttribute('href'));
}
Upvotes: 2
Reputation: 1392
For loop should iterate from 0 to length-1
Condition in for
loop should be i < all_videos.length
instead of i <= all_videos.length
The correct line should be:
for(i = 0; i < all_videos.length; i++) {
Upvotes: 1