Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

single onclick function for buttons with a similar id pattern - JavaScript

I want to reduce the code.

function one() {
 console.log("hai");
}

document.getElementById('dealsButton_1').onclick = one;
document.getElementById('dealsButton_2').onclick = one;
//I  want the above 2 lines of code reduced to one.

A single function for on click on 'dealsButton_*' patterned id elements. How can I do this. The elements are dynamically loaded.

like image 493
Anoop Mayampilly Muraleedharan Avatar asked Jun 21 '26 17:06

Anoop Mayampilly Muraleedharan


1 Answers

You can use querySelectorAll and the selector [id^=dealsButton_] to add the event listener in a single line - see demo below:

function one() {
 console.log("hai");
}

Array.prototype.forEach.call(
  document.querySelectorAll('[id^=dealsButton_]'), function(e) {
  e.addEventListener('click', one);
});
<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>

If the markup is dynamically loaded you can base it on a static element like this:

function one() {
  console.log("hai");
}

document.addEventListener('click', function(e) {
  if (e.target && /^dealsButton_/.test(e.target.id))
    one();
})

// dynamically add
document.body.innerHTML = `<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>`;
like image 164
kukkuz Avatar answered Jun 24 '26 05:06

kukkuz