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?

Answers:

Answer

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>

Answer

You can use querySelectorAll:

var elements = document.querySelectorAll('#test1, #test2');
for (var i=0, iLen=elements.length; i<iLen; i++) {
  // add listeners to elements[i];
}

Or if you want to mix host objects with native methods (not a good idea but…):

[].forEach.call(document.querySelectorAll('#test1, #test2'), function(el) {
  // attach listener to el
});

But event delegation may be a better idea than attaching the same listener to multiple elements.

Answer

Bind a handler to the parent and use event delegation. http://javascript.info/tutorial/event-delegation

Answer

Build an array of selectors then iterate through it adding the event listeners. Also put your alert or whatever action you want into a function. DEMO

var selectors = new Array("test1", "test2");

for(var i=0; i < selectors.length; i++) {
    var temp = document.getElementById(selectors[i]);
    temp.addEventListener('click', function() {
        clickaction(this.innerHTML);
    });
}

function clickaction(content) {
    alert(content);
}
Answer

Event delegation with indexOf polyfill if necessary.

var arrIDsToWatch = ["test1", "test2", "test5"];

// indexOf Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Compatibility
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {
    var k;
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }
    var O = Object(this);
    var len = O.length >>> 0;
    if (len === 0) {
      return -1;
    }
    var n = +fromIndex || 0;
    if (Math.abs(n) === Infinity) {
      n = 0;
    }

    if (n >= len) {
      return -1;
    }
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

    while (k < len) {
      if (k in O && O[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}


document.getElementById('parent').onclick = function(e) {
  e = e || event
  var target = e.target || e.srcElement
  var targetID = target.id;
  if (arrIDsToWatch.indexOf(targetID) > -1) {
    alert(target.innerHTML);
  }
}
<div id="parent">
  <div id="test1">test1</div>
  <div id="test2">test2</div>
  <div id="test3">test3</div>
  <div id="test4">test4</div>
  <div id="test5">test5</div>
</div>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.