In the continuation of the study of the dark world javascript I ask for help in this question: there is an array of buttons (like a calculator)

<button>1</button><button>2</button><button>3</button><button>4</button><button>5</button><button>6</button><button>7</button><button>8</button><button>9</button><button>0</button> 

need when you press the key to read the value of the digit. I tried this method:

 javascript code: var buttons = document.getElementsByTagName('button'); buttons.addEventListener('click', function(e){ console.log(e.target.innerHTML); }); 

what is the error in the console

Uncaught TypeError: Object #NodeList has no method 'addEventListener'

indicating the line

 buttons.addEventListener('click', function(e){ 

I can not find the info, maybe I just do not know where to dig. I understand that he does not want to bind the handler to the collection of items. Plz tell me

  • one
    Ask yourself what is in the buttons variable: an array or an element? How does an event tie to an item? - lampa
  • Of course a collection of buttons i. You want to say that you need to do something of type function (event) {for (var i = 0; i <buttons.length; i ++) {buttons [i] .addEventListener ('click', function (e) {console. log (e.target.innerHTML);})}} ?? - LivAlex
  • and how then to make this function work when you click on the button? what to hang it on document.addEventListener? - LivAlex
  • 2
    var buttons = document.getElementsByTagName ('button'); for (var i = 0; i <buttons.length; i ++) {buttons.addEventListener ('click', function () {console.log (this); // this will point to the button}, false); } And it can be a little different: <div id = 'btns'> <button> </ button> ... </ div> js: var btns_container = document.getElementById ('btns'); btns_container.addEventListener ('click', function () {if (e.target.tagName.toLowerCase () == 'button') {console.log (e.target);}}, false); - lampa
  • I don’t want to bother with id, because there are a lot of buttons, hanging on each id is just the same as describing each button through if () {} else {} :) thanks for the hint, everything worked out like you and Comrade #Histo2 suggested - LivAlex

1 answer 1

 window.onload = function (){ var k = document.getElementsByTagName("button"); for(var i = 0; i < k.length; i++) k[i].onclick = function (){ alert(this.innerHTML); } } 

And so?

  • so it works so, I understand correctly? window.addEventListener ('DOMContentLoaded', function () {var buttons = document.getElementsByTagName ('button'); for (var i = 0; i <buttons.length; i ++) {buttons [i] .addEventListener ('click' , function (e) {console.log (e.target.innerHTML);})}}); - LivAlex