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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…