admin管理员组

文章数量:1287941

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.

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.

Share Improve this question asked Jan 23, 2018 at 19:57 pinksharpiipinksharpii 5271 gold badge8 silver badges19 bronze badges 2
  • 1 Can you reproduce the issue at stacksnippets? – guest271314 Commented Jan 23, 2018 at 20:00
  • 1 All of these work fine. Your problem is elsewhere. – Jordan Running Commented Jan 23, 2018 at 20:10
Add a ment  | 

4 Answers 4

Reset to default 6
Array.from(HTML_COLLECTION).forEach(function (element) {
  console.log(element);
});

this works for me

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

You could also use an EventListener

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

O

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); })

本文标签: arraysHow to iterate through HTMLCollection in JavascriptStack Overflow