I have created an element using document.getElementsByClassname, and would like to add a onclick event to this element, so that when someone clicks on this element onclick function should be called.
I tried with event listener, but this will execute even when I don't click on any function. Using jQuery we can do that by binding a click event, but I my requirement is in javascript/
Thanks!
element.addEventListener("click", alert('clicked'), false);// Add onclick eventListener
var element= document.getElementsByClassName('classname');
We can bind a JavaScript function to a div using the onclick event handler in the HTML or attaching the event handler in JavaScript. Let us refer to the following code in which we attach the event handler to a div element. The div element does not accept any click events by default.
The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute a JavaScript's function when an element gets clicked. This event can be used for validating a form, warning messages and many more. Using JavaScript, this event can be dynamically added to any element.
The onclick attribute is part of the Event Attributes, and can be used on any HTML elements.
getElementsByClassName
returns an HTMLCollection
, so even though you have only one element with that classname in DOM, you have to retrieve it with index 0:
var element = document.getElementsByClassName('classname')[0];
element.addEventListener("click", function(e) {
alert('something');
}, false);
Alternatively, since you only have one element with the classname, you can safely use querySelector
, which will return the first match element.
var element = document.querySelector('.classname');
^
element.addEventListener("click", function(e) {
alert('something');
}, false);
Please note the dot in above code. querySelector
accepts a CSS selector string as a parameter.
Try this:document.getElementsByClassName
always returns array of elements.
var element= document.getElementsByClassName('classname');
for(var i=0;i<element.length;i++){
element[i].addEventListener("click", function(){alert('clicked')}, false);
}
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