0

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?

1

1 Answer 1

2

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.