I try the code below but when i click button does not show the alert message!
let clickButton = document.getElementsByClassName("buttonClass");
clickButton.onclick = clickFunc;
function clickFunc(){ alert("hello")};
console.log(clickButton);
i create buttons with document.createElement
I have try:
To choose only one button like this let clickButton = document.getElementsByClassName("buttonClass")[1];
but nothing
Also i have try to get element by tagname, loop with a length of buttons, and addeventlistener, but nothing again
let buttons = document.getElementsByClassName("buttonClass"); for (var i = 0; i < buttons.length; i++) { buttons.item(i).addEventListener('click', function(e) { alert("hello"); }); }
<button type="button" class="buttonClass">button 1</button> <button type="button" class="buttonClass">button 2</button> <button type="button" class="buttonClass">button 3</button> <button type="button" class="buttonClass">button 4</button> <button type="button" class="buttonClass">button 5</button>
Since your targeting by class, you get an array of elements. So you have to iterate and attach click events to each element as show below;
let buttons = document.getElementsByClassName("buttonClass");
for (var i = 0; i < buttons.length; i++) {
buttons.item(i).addEventListener('click', function(e) {
alert("hello");
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.