Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a onclick event to an element using javascript

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');
like image 479
221B Avatar asked Nov 16 '13 12:11

221B


People also ask

Can I add an onclick event to a div?

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.

Can we use onclick in JavaScript?

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.

Which is the correct attribute to attach a click event to an element?

The onclick attribute is part of the Event Attributes, and can be used on any HTML elements.


2 Answers

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.

like image 177
Leo Avatar answered Oct 17 '22 05:10

Leo


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);   
 }
like image 23
Vicky Gonsalves Avatar answered Oct 17 '22 06:10

Vicky Gonsalves