Javascript .map() is not a function
getElementsByClassName()
returns an HTMLCollection
not an Array
. You have to convert it into a JavaScript array first :
allImgs = Array.prototype.slice.call(allImgs);
// or
allImgs = [].slice.call(allImgs);
// or (thanks @athari)
allImgs = Array.from(allImgs);
// or (thanks @eliaz-bobadilla)
allImgs = [...allImgs]
Another option would be to use map
directly:
[].map.call(allImages, function() { ... });
However, what you are doing is better achieved with Array.prototype.forEach
.
By using getElementsByClassName, I get an array.
No, you don't.
You get a live HTMLCollection. This is array-like but is not an array.
Since it is sufficiently array-like, you can apply the map
method from a real array.
var text_content = [].map.call(
document.getElementsByClassName("sdf"),
function (currentValue, index, collection) {
return currentValue.innerHTML;
}
);
console.log(text_content);
<p class="sdf">foo</p>
<p class="sdf"></p>
<p class="sdf">bar</p>
<p class="sdf"></p>
<p class="sdf"></p>