Doug Fir
Doug Fir

Reputation: 21232

Javascript selector with Regular Expression

I would like to add an event listener to 2 buttons. Their ids are:

authCreateAcctConfirmNoBtn
authCreateAcctConfirmYesBtn

How would I do the following, I imagine I am close:

authCreateAcctConfirm(No|Yes)Btn.addEventListener('blur', function() {...

I don't know how to tell the browser that the object to attach to is a regular expression?

Upvotes: 0

Views: 314

Answers (1)

Christoph
Christoph

Reputation: 51201

You need to select the elements first. This is done via document.querySelector.

I would avoid crazy Regex magic and choose the straightforward way. The easiest solution would look like this:

document.querySelector("#authCreateAcctConfirmYesBtn").addEventListener("blur",func);
document.querySelector("#authCreateAcctConfirmNoBtn").addEventListener("blur",func);

function func(){
   /* stuff here */
}

To select both at once, you could use querySelectorAll and use this selector:

var elements = document.querySelectorAll("#authCreateAcctConfirmYesBtn, 
                                          #authCreateAcctConfirmNoBtn");

You now have to iterate over the returned NodeList resultset with a straightforward for loop or a borrowed Array method:

Array.prototype.forEach.call(elements,func);

Here you get the element handed over as first parameter in func.

Upvotes: 1

Related Questions