Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  159] [ 1]  / answers: 1 / hits: 15211  / 10 Years ago, tue, december 16, 2014, 12:00:00

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?


More From » jquery

 Answers
10

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>




[#68477] Friday, December 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
megb

Total Points: 230
Total Questions: 113
Total Answers: 100

Location: Tokelau
Member since Sun, May 7, 2023
1 Year ago
;