Polly Polly - 1 year ago 133
Javascript Question

How put regex in getElementByIds

Suppose to have more buttons:

<input type="button" id="number_1" value="A">
<input type="button" id="number_2" value="B">

<input type="button" id="number_n" value="N">


I want get click when the user click on them. So I would use something like this code (without Jquery):

var button=document.getElementById('[id^=number]');
button.onclick=function(){alert("HIII")};


But this code is not work. Anyone can help?

Answer Source

Attribute selectors

document.querySelectorAll()

Array.prototype.forEach()

Function.prototype.call()

EventTarget.addEventListener()

Array.prototype.forEach.call(document.querySelectorAll('[id^=number_]'), function (element) {
  element.addEventListener('click', function (e) {
  	alert(e.target.id);
  });
});
<input type="button" id="number_1" value="A">
<input type="button" id="number_2" value="B">
<input type="button" id="number_n" value="N">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download