How to add a onclick event to an element using javascript
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);
}
You have to pass reference of a function instead of adding inline alert.
var element= document.getElementsByClassName('classname');
function doSomething() {
alert('clicked')
}
// add event listener to element
element.addEventListener("click", doSomething, false);
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.
You can use .attr()
jquery method for this:
$('.classname').attr("onClick", "javascript:alert('clicked'); return false;");
Try this
JavaScript
var element= document.getElementsByClassName('classname');
element[0].onclick = function() { alert('Hello'); };//-- here i used "[0]" to refer first matched element
Try with javascript