Search code examples
javascripthtmltagsaddeventlistenergetelementsbytagname

Why cant't I combine document.getElementsByTagName and .addEventListener in this case?


I am making a little power point, but I am stuck. When one <input> is clicked, I want to change a variable. I tried this :

HTML :

<input size="40">
<input size="40">

JAVASCRIPT :

inputClicked = false;
document.getElementsByTagName("INPUT").addEventListener("click", function() {
  inputClicked = true;
});

var inputClicked = false;
document.getElementsByTagName("INPUT").addEventListener("click", function() {
       inputClicked = true;
       alert(inputClicked);
});
<input>
<input>

I you run this hided snippet, you will see, when the <input>s are clicked, no alert pops up. plz show me my error, or another way to do it....


Solution

  • The good thing about using focus instead of click is that you can use the tab key.

    document.querySelector('input').addEventListener('focus', function (event) {
      console.log(event.target)
    }, false)
    

    If you have more than one input tag to handle:

    const inputs = Array.from(document.querySelectorAll('input'))
    
    inputs.forEach(function (input) {
      input.addEventListener('focus', function (event) {
        console.log(event)
      }, false)
    })
    

    Explanation: document.querySelectorAll('input') returns a NodeList which is not an array. Array.from() converts the NodeList into an array.