Minh Bang
Minh Bang

Reputation: 153

call function with className.onclick JS

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?

Upvotes: 3

Views: 18593

Answers (5)

Mr. X
Mr. X

Reputation: 274

You either loop over all the elements referenced by the el variable and attach the event handler on each element as you see fit, or delegate the event handler to document for example and fire it accordingly.

Either way you choose, you should note that onclick prop and its siblings are not defined on HTMLCollection instances or any other array-like objects returned by querySelectorAll() etc.

//ES6 syntax, registering a click event handler on each element 
[].slice.call(document.getElementsByClassName('elements')).forEach(ele => ele.onclick = () => console.log('whatever'));

//ES6, Event delegation
document.addEventListener('click', eve => {
  eve.target.classList.contains('elements') ? console.log('whatever') : undefined ; 
});

Upvotes: 1

mohamedrias
mohamedrias

Reputation: 18566

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

Upvotes: 4

zfrisch
zfrisch

Reputation: 8660

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.

Upvotes: 1

John williams
John williams

Reputation: 731

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

Upvotes: 1

SurrealSyntax
SurrealSyntax

Reputation: 1375

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.

Upvotes: 9

Related Questions