I'm writing a function to gather all anchor elements and write listeners for them. If I refresh the browser (latest versions of Chrome and Firefox on Mac), sometimes the collection of elements is displayed differently and causes my call to Array.prototype.slice to return an empty array.
function toArray(arr) { return Array.prototype.slice.call(arr); }
let anchors = toArray(document.getElementsByTagName('a'));
for (var i = 0; i < anchors.length; i++)
{
anchors[i].addEventListener('click', clicked, false);
}
console.log(document.getElementsByTagName('a'));
console.log(anchors);
When working properly (the listeners are added), the console looks like this:
But when I refresh the browser, much of the time it comes back looking like this:
If I expand the array output, it looks like this:
Why are they sometimes different? Is there a way to always get the correct result?