I’m learning javascript at the moment and the code below isn’t producing the results I thought it would:
var links = document.getElementsByTagName("a");
for(i=0; i<links.length; i++) {
document.write(links[i]);
}
When I run this code, it writes 1 element from the array. I want it to return everything (there are over 1,000 in links)
What did I do wrong?
links is a live NodeList (see .getElementsByTagName()). Any change to the links on the page will be reflected immediatly in the list.
With the first
document.writeyou’re overwriting the current document (if used after the document has loaded) so thelinkslist will be empty.Use
console.log()instead ofdocument.writeand have a look at the Javascript console of you’re browser.