Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get clicked button's id by class name without jquery

Tags:

javascript

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

HTML

<form action="" method="post" >
    <input type="button" id="btn_1" class="cls_btn" value="Click Me" />
    <input type="button" id="btn_2" class="cls_btn" value="Click Me" />
    <input type="button" id="btn_3" class="cls_btn" value="Click Me" />
</form>

javascript

I want id of button when it clicked.
my js code looks like

<script >
    document.getElementsByClassName('cls_btn').onclick = function(){
        alert(this.id);
    };
</script>
like image 431
Ekramul Hoque Avatar asked Sep 30 '13 10:09

Ekramul Hoque


2 Answers

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)

like image 91
Saturnix Avatar answered Sep 30 '22 13:09

Saturnix


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

like image 33
letiagoalves Avatar answered Sep 30 '22 14:09

letiagoalves