I would like to make that when you click the button, the code should alert the name inside of a class move. But my code does not work correctly, and the console says "Cannot read property 'getElementsByClassName' of undefined". Is there something wrong in my javascript code?? Thanks.
Part of my javascript code;
for(var i=0; i<4; i++){
document.getElementsByClassName("moves")[0].getElementsByTagName("BUTTON")[i].onclick
= alert(document.getElementsByClassName("moves")[0].document.getElementsByClassName("move")[i].textContent);
}
Part of my HTML code;
<div class="moves">
<button>
<span class="move">a</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">b</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">c</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">d</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
</div>
A couple things to note:
1 - When you were passing an alert()
to the click handler, it was being called immediately. You need to wrap it in a function.
2 - Using this
, you don't need to reselect the element from the very top, you can go from where you currently are in the scope.
for (var i = 0; i < 4; i++) {
document.getElementsByClassName("moves")[0].getElementsByTagName("BUTTON")[i].onclick = function() {
alert(this.textContent.trim())
};
}
<div class="moves">
<button>
<span class="move">a</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">b</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">c</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">d</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
</div>