2

I am using:

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

to get all links on the page. We need to modify a few.

if I console log links, I get an HTMLCollection of 100+ a elements. If I console log links.length, it's 0.

I've tried everything I can find to convert this to an array but nothing is working.

Array.from(links)

Array.prototype.slice.call(links)

[].forEach.call(links, function (el) {...});

HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];

HTMLCollection.prototype.forEach = Array.prototype.forEach;

These all produce an empty array.

Additionally var links = document.querySelectorAll('a'); produces an empty NodeList.

I've run out of options. The initial links variable is very much not empty. So I don't understand why all of these suggested options don't work. Additionally, jQuery is not an option for us.

2
  • 1
    Can you reproduce the issue at stacksnippets? Commented Jan 23, 2018 at 20:00
  • 1
    All of these work fine. Your problem is elsewhere. Commented Jan 23, 2018 at 20:10

4 Answers 4

6
Array.from(HTML_COLLECTION).forEach(function (element) {
  console.log(element);
});
Sign up to request clarification or add additional context in comments.

Comments

4

this works for me

var links = document.getElementsByTagName('a');
var result = [].slice.call(links)

2 Comments

by the way your listed other options work as well, are you sure your problem is not in other place?
I had to move my code to the footer, which does not make a ton of sense to me. It was able to find all the links, so why not iterate through them? unless the code is in the footer area...
1

You could also use an EventListener

window.addEventListener('load', function () {
  var links = document.getElementsByTagName('a');
  console.log(links);
}

O

Comments

0

Almost had it: var linksAsArray = Array.prototype.slice.call(links, 0)

Also, as an alternative, you can write a helper function to avoid needing to convert nodelists to arrays all of the time. For example,

function each(elems, fn){
  var i = -1;
  while(++i < elems.length){
    fn(elems[i])
  }
}

each(links, function(link){ console.log(link); })

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.