Paul Dessert
Paul Dessert

Reputation: 6389

printing elements with javascript

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?

Upvotes: 0

Views: 52

Answers (1)

Andreas
Andreas

Reputation: 21881

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.write you're overwriting the current document (if used after the document has loaded) so the links list will be empty.

Use console.log() instead of document.write and have a look at the Javascript console of you're browser.

var links = document.getElementsByTagName("a");

for(i=0; i<links.length; i++) {
    console.log(links[i]);
}

Upvotes: 2

Related Questions