Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Target multiple selectors in JS only

I am trying to implement a click event on my site without jQuery.

I want to target multiple selectors.

In jQuery this can be done by simply comma seperating the items as shown below.

jQuery(document).on('click', '#test1, #test2', function (event) {
    alert($(this).text());
});

How can this easily be done in plain javascript?

I have tried the below which works but it seems like there should be a simpler way especially if I want more than an alert to occur on click? I want to target more than one specific selector not all divs for example

var test1 = document.getElementById('test1');
var test2 = document.getElementById('test2');

if (test1.addEventListener || test2.addEventListener) {
    test1.addEventListener('click', function(event) {
        alert(this.innerHTML);
    });
    test2.addEventListener('click', function(event) {
        alert(this.innerHTML);
    });

    /* this only works when you click on test2
    (test1,test2).addEventListener('click', function(event) {
        alert(this.innerHTML);
    });
    */
    /* this only works when you click on test2
    (test1.addEventListener),(test2.addEventListener)('click', function(event) {
        alert(this.innerHTML);
    });        
    */
}

    var test1 = document.getElementById('test1');
    var test2 = document.getElementById('test2');
    if (test1.addEventListener || test2.addEventListener) {
        test1.addEventListener('click', function(event) {
            alert(this.innerHTML);
        });
        test2.addEventListener('click', function(event) {
            alert(this.innerHTML);
        });
    }
<div id="test1">test1</div>
<div id="test2">test2</div>

Is there a way to comma seperate the selectors, or setup all selctors before running the code like you can with jQuery?

like image 812
ak85 Avatar asked Dec 16 '14 03:12

ak85


1 Answers

This would be basically the equivalent code minus all the browser checking:

document.body.addEventListener("click", function(e) {  //bind event to the document
   var targ = e.target;  //get what was clicked on
   var id = targ.id;  //grab the id
   if (["test1","test2"].indexOf(id)!==-1){ //see if it is one of the ids
       alert(targ.textContent);    //show the text
   }
}, false);
<div id="test1">test 1</div>
<div id="test2">test 2</div>
<div id="test3">test 3</div>
like image 98
epascarello Avatar answered Nov 15 '22 01:11

epascarello