最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - call function with className.onclick JS - Stack Overflow

programmeradmin1浏览0评论
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?

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?

Share Improve this question asked Apr 6, 2015 at 16:30 Minh BangMinh Bang 1532 gold badges4 silver badges9 bronze badges 2
  • that method returns an array of elements... even if there is only one element with that classname. – El Guapo Commented Apr 6, 2015 at 16:31
  • I just found that jquery could help me with this. Thanks for everybody answers , I've learned something new – Minh Bang Commented Apr 7, 2015 at 10:01
Add a comment  | 

5 Answers 5

Reset to default 9

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.

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

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

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 ; 
});
发布评论

评论列表(0)

  1. 暂无评论