Reputation: 371
I am new here (and new to JavaScript), so please excuse my super basic questions. I have a HTML page with different images that all share a class on it. By using getElementsByClassName, I get an array. I want to add an event listener to each of the cells in the array by using the .map() function.
This is what I have:
window.onload = function(){
var allImgs = document.getElementsByClassName("pft");
var newImgs = allImgs.map(
function(arrayCell){
return arrayCell.addEventListener("mouseover, functionName");
}
);
};
This keeps showing the error "allImgs.map is not a function" even when I change the inner function to something that doesn't include the event listener.
I have another version of this code where I just loop through the array cells within window.onload and add the event listener to each of them that way and it works. Why isn't the .map() function working? Can it not be used in window.onload?
Upvotes: 34
Views: 74788
Reputation: 9357
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]
Upvotes: 48
Reputation: 1
var elms = document.querySelectorAll('.demo');
for(var i = 0; i < elms.length; i++) {
var elm = elms[i];
elm.onmouseleave = function() {
this.style.color = "#000";
}
elm.onmouseover = function() {
this.style.color = 'red';
}
}
.demo {
cursor:pointer;
}
<div>
<p class="demo">paragraph one</p>
<p class="demo">paragraph two</p>
<p class="demo">paragraph three</p>
<p class="demo">paragraph four</p>
<p class="demo">paragraph five</p>
<p class="demo">paragraph six</p>
</div>
Upvotes: 0
Reputation: 1296
Compact syntax:
[...document.getElementsByClassName("pft")].map(arrayCell => arrayCell.addEventListener("mouseover", "functionName"))
Upvotes: 4
Reputation: 957
Another option would be to use map
directly:
[].map.call(allImages, function() { ... });
However, what you are doing is better achieved with Array.prototype.forEach
.
Upvotes: 6
Reputation: 943158
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>
Upvotes: 9