How do I access the element that I have created in javascript?

  • 0
    https://jsfiddle.net/b3v6ky1z/
    Hello everyone! Please tell me when you click on the button, I create an element through js and give it a class
    button2 = document.createElement('button')
            button2.setAttribute("class", "buttonDelete");  
            tr.appendChild(button2)
            button2.innerHTML = 'Delete');


    Now it is necessary to delete the element when clicking on this class, but it does not even see this class (
    buttonDelete.addEventListener('click',function(){
        console.log('ggwp');
    })
    JavaScript Ariana Baxter, Jun 14, 2020

  • 1 Answers
  • 0

    1. Not setAttribute ("class", "buttonDelete"); but classList.add ("buttonDelete");

    2. Insert an element into the document ( tr.appendChild (button2) ) last, that is, after changing the content button2.innerHTML = 'Delete'); < br />

    3. Your problem is that buttonDelete contains a list of all buttons that were at the time the querySelector was called. It is not a dynamic value. We called querySelector, it returned all the buttons that were on the page at the moment. It is logical that there are no new buttons in this selection. To solve the problem you need:


      1. Move all the logic for removal into a separate function, let's call it removeCallback .

      2. Add an event listener separately for each button at the time of its creation:
        button2.addEventListener('click', removeCallback)
        tr.appendChild(button2)






    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!