call function with className.onclick JS

11,436

Solution 1

You cannot attach an event listener to an array of objects, which is that function will be returning.

Instead, loop through the list returned and attach the event listener to each item.

Solution 2

Instead of document.getElementsByClassName, it's better to use document.querySelectorAll as it's getElementsbyClassName returns you a live HTMLCollection whereas querySelectorAll returns you static NodeList.

 var el = document.querySelectorAll(".elements"); // this element contains more than 1 DOMs.
    for(var i =0; i < el.length; i++) {
        el[i].onclick = function() { console.log("target name should be here")};
    }

In case you wan to track the element count inside your event handler, then its better to wrap the event handler inside IIFE

 var el = document.querySelectorAll(".elements"); // this element contains more than 1 DOMs.
 // as it contains a NodeList, it's desirable to iterate through the list and bind events.                   
  for(var i =0; i < el.length; i++) {
      // Inside the event handler function, if you want to access i, then its better to wrap it inside IIFE
      (function(i) {
            el[i].onclick = function() { console.log("target name should be here")};   
       })(i);
   }

Solution 3

Your selector returns an array of elements so you need to loop them.

var els = document.getElementsByClassName("elements"); 
// loops els
for(var i = 0, x = els.length; i < x; i++) {
    els[i].onclick = function(){
        // do something
        console.log('target name should be here');
    }
}

Solution 4

var el = document.getElementsByClassName("elements"); 
// this element contains more than 1 DOMs.
for(var i=0;i < el.length;i++) {

el[i].addEventListener("click", function() { 
console.log("My index number is: " + i)});
}

This will loop through the node list returned by the query and return the index number on click into the console. If you need to get a specific element and the page is static(meaning the indexes are going to be the same) you can grab the index number through this process, then change the code so that on load you specify:

var el = document.getElementsByClassName("elements"); 
// this element contains more than 1 DOMs.
var i = indexNumber; 
el[i].addEventListener("click", function() { 
// do whatever
});

where var i is the target index number.

Share:
11,436
Minh Bang
Author by

Minh Bang

Updated on June 05, 2022

Comments

  • Minh Bang
    Minh Bang almost 2 years
    var el = document.getElementsByClassName("elements"); // this element contains more than 1 DOMs.
    el.onclick = function() { console.log("target name should be here")};
    

    So I don't want to have inline JS, I want to fire function when it click to a specific DOM that has same class to any other elements.
    Could anyone help please?