Get clicked button's id by class name without jquery

document.getElementsByClassName returns a list of DOM objects. Applying .onclick to a collection of html items results in nothing. No error is thrown but you'll not see the expected result anyway.

Try this:

var buttons = document.getElementsByClassName('cls_btn');

for (var i = 0; i < buttons.length; i++){
    buttons[i].onclick = function(){ alert(this.id) };
}

See here: JSFiddle


I don't want to use jquery for this small task.

Note that jQuery can handle the same loop for you. No need to iterate over the list: just provide the selector and it will be done for you.

$('.cls_btn').click(function() {
  console.log($(this).attr('id'));
});

See here: JSFiddle (jq)


getElementsByClassName returns a list of DOM elements so you need to loop it and add an event listener to each:

var buttons = document.getElementsByClassName('cls_btn');
for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', function() {
        alert(this.id);
    });
}

Working demo

Tags:

Javascript