Xriuk
Xriuk

Reputation: 392

Onclick event for multiple buttons

I have more than one <span> with class="section_title", I want to set up a unique event listener for all of them which runs a function onclick. How can I do this? (preferably without jQuery)

Upvotes: 0

Views: 6730

Answers (2)

Anand Jha
Anand Jha

Reputation: 10714

try this,

   <span class="yourClass"/>
   <span class="yourClass"/>

   var spanSelector= document.querySelectorAll('.yourClass');//work in all browser

    for (var i = 0, i<  spanSelector.length;  i++) {
        spanSelector[i].onClick= yourFn// where yourFn is function name that will be colled on click of span.
    }

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382122

var f = function(){
    // do something
}
var elems = document.getElementsByClassName("section_title");
for (var i=0, len=elems.length; i < len; i++) elems[i].onclick = f;

Or for broader compatibility, use .querySelectorAll(), which takes a CSS type of selector.

var f = function(){
    // do something
}
var elems = document.querySelectorAll(".section_title");
for (var i=0, len=elems.length; i < len; i++) elems[i].onclick = f;

Upvotes: 3

Related Questions