Help me figure it out; I can't understand what the error is. In general, the task is the following; I need to pull an element from html by clicking on it and suppose the value of this element is output by an alert.

window.onload=function(){ gtClassName('B'); } function gtClassName(nameClass){ with(this){ ObjectAdd = document.getElementsByClassName(nameClass); ObjectAdd.addEventListener('click' , outDate); function outDate(){ alert(this); } } } 

I did this with jq , but it doesn't work on pure js . When sampling by id it works, and by class it gives an error in the console:

TypeError: ObjectAdd.addEventListener is not a function;

And if you specify ObjectAdd with an index, that will also work. Tell me how to make it so that the process does not require access to the cycles, otherwise how can this be done through this ?

Thank you in advance!

    2 answers 2

    It is solved with the help of iteration as it was said by the user Mr. Brightside, here’s the solution:

      window.onload = function(){ var p = new getClassAndBinding(); p.getValAndClick(Имя класса в HTML); } function getClassAndBinding(){ this.getValAndClick = function(NameClass){ this.getCls = document.getElementsByClassName(NameClass); for(i = 0;i<this.getCls.length;i++){ this.getCls[i].addEventListener('click' , function(){ alert(this.value); });} }} 

      Of course, there will be an error, because an array of objects is returned to you, with a given class (read the doc here ). If you substitute ObjectAdd [0], then the event should fire for the first element.

      You can use something like this:

       window.onload=function(){ document.addEventListener('click' , function(e) { e = e || window.event; var target = e.target || e.srcElement, text = target.textContent || text.innerText; alert(text); }); }; 

      However, here the event will display a notification with any click to any place in the document.

      According to the above documentation, using getElementsByClassName allows you to get the children of only the desired element, and process clicks, respectively, only for them. However, I am afraid, we cannot do without iteration here.

      • Thank you, decided .. - shimba
      • You can post your decision here so that other participants, faced with the same task, can take advantage of your decision. - Mr. Brightside
      • @ Mr.Brightside, it’s better not to say an array, but a collection - Grundy