BenQCat BenQCat - 2 years ago 83
HTML Question

AddEventListener for multiple elements doesn't work with "focus" event

I'm guessing I have a basic error in thinking but I just can't get around it.

I have a couple of text fields which I want to add an EventListener to.
I put them all in one class and added the EventListener to this class.
Everyhing works perfect when event of choice is "click". But when I change it to "focus" nothing happens. Why is that?

this works:

document.getElementById('parent').addEventListener('click', emptyField, false);

this doesn not:

document.getElementById('parent').addEventListener('focus', emptyField, false);

text fields:

function emptyField(e){
var clicked =;
if (clicked.value == {

if ('password') {

<class id="parent">
<input type="text" name="USERNAME" id="username" value="USERNAME"><br>
<input type="text" name="PASSWORD" id="password" value="PASSWORD" ><br>

Answer Source

I think you have to use querySelectorAll() that will return all the inputs :

var fields = document.querySelectorAll('#parent input');

And use loop to attach focus event to every field :

for (var i = 0; i < fields.length; i++) {
    fields[i].addEventListener('focus', emptyField, false);

Hope this helps.

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