How to add a onclick event to an element using javascript

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.

Leave a Comment