15

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');
Ishan Jain
  • 8,063
  • 9
  • 48
  • 75
221B
  • 831
  • 2
  • 11
  • 21

7 Answers7

20

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.

Matt Hampel
  • 5,088
  • 12
  • 52
  • 78
Leo
  • 13,428
  • 5
  • 43
  • 61
  • IMHO, I would add that if you can assert that you will have only one element with a classname, then it should be an id and not a class – Logar Feb 23 '17 at 16:58
  • 1
    @Logar `id` implies that you want to identify an HTML element. It doesn't mean every unique element in the document should be labeled with an id. You don't necessarily do this to `` or ``, do you? In regards of "semantic web" it's a bad practice. – Leo Jun 04 '21 at 02:13
6

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);   
 }
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
  • in my case, there are no array of elements, so only one element is there hence I dont need any array. I have used eventlistener but when I deploy this code in the website, while the page is loading my function executes, but I want my function to be executed only when user clicks on the element – 221B Nov 16 '13 at 12:10
  • Read more about `getElementsByClassName` https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName – Vicky Gonsalves Nov 16 '13 at 12:14
  • exactly as instructed in the given page I have assigned some value to my element. but now the question is, how to I bind a onclick event for the element I have created – 221B Nov 16 '13 at 12:16
2

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);
Punit Sachan
  • 563
  • 6
  • 16
1

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

Ishan Jain
  • 8,063
  • 9
  • 48
  • 75
0

You can use an event delegation or DOMNode.matches.

document.addEventListener('click', function(e) {
   if (e.target.className == 'classname') // if (e.target.matches('.classname'))
   {
       //do something
   }
});
xercool
  • 4,179
  • 6
  • 27
  • 33
0
Please try the following:

var rows = 3;
var cols = 3;
var defaultVal=0;
var mainDiv=document.getElementById("mainDiv")
var arr = []
for (var i = 0; i < rows; i++) {
    arr[i] = [];
  for(var j=0;j<cols;j++){
    arr[i][j]=defaultVal++;
    var element=document.createElement("input");
    element.type="button";
    element.className="left";
    element.addEventListener("click", testFunction, false);
    element.value=arr[i][j];
    mainDiv.appendChild(element);


  }


}
function testFunction(){
    alert('hi')
}

//Use element.addEventListener("click", testFunction, false); 
//Use testFunction and not testFunction() as this "()" invokes the function
Nishanth Suresh
  • 101
  • 1
  • 3
0

I was able to add an onclick event to an element using following javascript code

list_title = document.createElement('UL');
list_title.onclick=function() {

    // place your code here
};
Jose Kj
  • 2,912
  • 2
  • 28
  • 40