Reputation: 71
I've seen some people having this problem but I can't find a solution that can fit my code. I'm trying to build a memory game using many <img>
tags inside a <div>
one, so that in Javascript I can make an addEventListener that can call the same function for different objects. But when I try to open it on Chrome it says:
main2.js:21 Uncaught TypeError: img_deck.addEventListener is not a function
Below is my code:
HTML:
<body onload="sortDeck()">
<div class="deck">
<tr>
<th> <img id="0" src="back.jpg"> </th>
<th> <img id="1" src="back.jpg"> </th>
<th> <img id="2" src="back.jpg"> </th>
<th> <img id="3" src="back.jpg"> </th>
</tr>
<tr>
<th> <img id="4" src="back.jpg"> </th>
<th> <img id="5" src="back.jpg"> </th>
<th> <img id="6" src="back.jpg"> </th>
<th> <img id="7" src="back.jpg"> </th>
</tr>
<tr>
<th> <img id="8" src="back.jpg"> </th>
<th> <img id="9" src="back.jpg"> </th>
<th> <img id="10" src="back.jpg"> </th>
<th> <img id="11" src="back.jpg"> </th>
</tr>
</div>
</body>
JS:
var img_deck = document.getElementsByTagName("DIV");
img_deck.addEventListener("click", clickCard);
Upvotes: 0
Views: 4385
Reputation: 1622
document.getElementById
will return an html element which id is same with param.
Whereas document.getElementsByTagName
returns the array of html elements which tags are same with the param.
So in your script,
var img_deck = document.getElementsByTagName("DIV");
img_deck.addEventListener("click" , clickCard);
img_deck will have the array of elements which tags are 'DIV'
So you should make a loop for img_deck and add event listener for every element inside that loop
like this
var img_deck = document.getElementsByTagName("DIV");
img_deck.forEach(function(elem){
elem.addEventListener("click", clickCard);
})
Upvotes: 2
Reputation: 801
As the method you are using suggests, getElementsByTagName
returns more than one element, as an array. You could iterate over this array like so:
const divs = document.getElementsByTagName("DIV");
for (const div of divs) {
div.addEventListener("click", clickCard);
}
Upvotes: 2