I don't want to use jquery for this small task.
<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>
I want id of button when it clicked.
my js code looks like
<script >
document.getElementsByClassName('cls_btn').onclick = function(){
alert(this.id);
};
</script>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With