简体   繁体   中英

Target any element of the elementsByClassName array?

I have a page which renders many divs of the same class name;

Is something like this possible without loop?

var elements = document.getElementsByClassName('className of divs');
elements[*].onclick = function(){
    alert('I can click any of the divs now!');
};

*=any number

A short and sweet way...

var elements = document.getElementsByClassName('className of divs');

[].forEach.call(elements, function(e){
     e.onclick = function(){
        alert('I can click any of the divs now!');
        };
});

If you want to add an event handler to each of the elements, then you need to access each of the elements and apply the event handler in turn. For this you must use a loop (or something loop-like such as map (note that since getElementsByClassName returns a HTMLCollection, not an array, it doesn't have a native map function).

Your other option is to use event delegation (where you put the event handler on an ancestor element, and then examine event.target and test for the class membership at event time instead of bind time).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM