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


i want reduce code.

function one() {  console.log("hai"); }  document.getelementbyid('dealsbutton_1').onclick = one; document.getelementbyid('dealsbutton_2').onclick = one; //i  want above 2 lines of code reduced one. 

a single function on click on 'dealsbutton_*' patterned id elements. how can this. the elements dynamically loaded.

you can use queryselectorall , selector [id^=dealsbutton_] add event listener in 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 markup dynamically loaded can base on static element 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>`;


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -