Hello. Tell me, please, how can I put an event handler (say, onclick ) to all elements that have a specific css- class set.
In other words, let's say there is a css- class myClass , on the page there is an element

 <input type="checkbox" class="myClass"/> 

How to install onclick handler for all elements with class myClass ?
Attention! Without the use of libraries.

    4 answers 4

    There is such a solution, more or less cross-browser ... UPD with @Ilya_Pirogov

     if (document.getElementsByClassName == undefined) { document.getElementsByClassName = function(className) { // реализация функции function x_getElementsByClassName(className){ var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)"); var elements = document.all; var returnElements = []; var current; var length = elements.length; for(var i=0; i<length; i++){ current = elements[i]; if(testClass.test(current.className)){ returnElements.push(current); } } return returnElements; } } } 
    • Works great !!! Thank! - Anton Mukhin
    • Firefox does not cope :(. Swears on document.all , says elements undefined. !!! - Anton Mukhin
    • here: var all = document.all || document.getElementsByTagName ('*'); I hate the fox, forgive me. - knes
    • Yes. But from the point of view of me as a user, it is convenient. Thanks for the addition. - Anton Mukhin
    • one
      If we talk about cross-browser compatibility, then it’s probably better to do so: if (document.getElementsByClassName == undefined) {document.getElementsByClassName = function (className) {// function implementation}} - Ilya Pirogov
     Elements = document.getElementsByClassName("someClass"); for(var i=0; i<Elements.length; i++) { Elements[i].onclick = eventFunction; } 
    • No, it does not work in slightly older browsers. =) In the new - yes. - knes
    • IMHO to write for browsers 10+ years ago IT IS BRED <br> Browsers who are not ie and which are younger than 10 years is your new? O_o - Zowie
    • And it worked! - Anton Mukhin

    Something like this, but it will not work very quickly :)

     for (i in document.all) { el = document.all[i]; if (el.className.indexOf('fl') != -1) { el.addEventListener('click', function() { alert('Hello!'); }, false); } } 

    Although it is better, of course, to check through the regulars.

       var divs = getElementsByTagName('div'); for (var i=0; i<divs.length; i++){ if(divs[i].cssClass="myClass") divs[i].onclick= function(){ } } 

      you can still see this answer

      • one
        divs [i] .cssClass = "myClass" - double equality is necessary =) Plus, if the element has two classes, the solution will not work - knes