Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  144] [ 6]  / answers: 1 / hits: 68559  / 11 Years ago, sat, november 16, 2013, 12:00:00

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');

More From » jquery

 Answers
1

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.


[#74254] Thursday, November 14, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayla

Total Points: 681
Total Questions: 102
Total Answers: 108

Location: Marshall Islands
Member since Tue, Sep 21, 2021
3 Years ago
tayla questions
Fri, Mar 5, 21, 00:00, 3 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Thu, Apr 9, 20, 00:00, 4 Years ago
;