-1

I'm trying to 'listen' to clicks on any input field using the snippet below

document.getElementsByTagName('input').onclick = function(){
    console.log('clicked an input field');
}

But nothing happens when I click on the input fields.

I double checked to make sure that input fields are being detected with getElementsByTagName using this snippet and it shows 200 objects

    elems = document.getElementsByTagName('input');
    console.dir(elems);

Screenshot from console:

enter image description here

Is there a reason why this would not work? I tried moving code to different sections to make sure that document is loaded when it runs.

Plain javascript, not using jquery

Robert Sinclair
  • 4,550
  • 2
  • 44
  • 46
  • are you sure you don't want onchange instead? – EugenSunic Apr 30 '20 at 07:25
  • Did you make sure that the script is not executed until the page has been loaded? Are the elements already in the DOM tree when the script is executed? – chriss Apr 30 '20 at 07:26
  • @chriss i believe so because i put it inside window.onload and it's run right below the elems = document.getElementsByTagName('input'); which returns 200 elements, so I think they're there – Robert Sinclair Apr 30 '20 at 07:27
  • @EugenSunic yep, I want to change the background color regardless of the field's value – Robert Sinclair Apr 30 '20 at 07:28
  • The question is a bit confusing, you know you're getting a collection, but I suppose you also know, that you can't click on that ..? – Teemu Apr 30 '20 at 07:29
  • @Teemu no i wasn't aware of that, i'll try attaching the onclick listener onto individual elements – Robert Sinclair Apr 30 '20 at 07:32

1 Answers1

2

getElementsByTagName returns a html collection.So you need to retrieve individual element and then attach event to it.

[...document.getElementsByTagName('input')].forEach((item) => {
  item.addEventListener('click', function() {
    console.log('clicked an input field');
  })
})

The three dots ... is spread syntax to convert the collection to array so that array methods like forEach can be used

Alternatively you can use normal for loop to attach event to the element

let inputs = document.getElementsByTagName('input');
for (let i = 0; i < inputs.length; i++) {
  inputs[i].addEventListener('click', function() {
    console.log(this.id);
  })
}
<input type='text' id='1'>
<input type='text' id='2'>
<input type='text' id='3'>
brk
  • 48,835
  • 10
  • 56
  • 78