'How do i delete buttons after theyre created and clicked

I'm trying to delete buttons from a table after they're created and clicked. I used two functions, one for the creation and one for the deletion, and so far only one button is deleted, the rest don't delete even after I created and clicked them I used the function 'ajouter' to create the button and append it to the table, then I used the 'test 'function to delete the button, so far, only one button is deleted. I couldn't figure it out

function ajouter() {
    let titre = document.getElementById('titre').value;
    let auteur = document.getElementById('auteur').value;
    let année = document.getElementById('année').value;
    let table = document.getElementById('myTable');


    let newRow = table.insertRow(1);
    let Cell1 = newRow.insertCell(0);
    let Cell2 = newRow.insertCell(1);
    let Cell3 = newRow.insertCell(2);


    Cell1.innerHTML = titre;
    Cell2.innerHTML = auteur;
    Cell3.innerHTML = année;


    var button = document.createElement("button");
    button.innerHTML = "Delete";
    button.setAttribute('id', 'buttons');
    Cell3.appendChild(button);
    return (false);
};



if (ajouter() == false) {
    buttons = document.getElementsByTagName('button');
    console.log(buttons + "test")
    for (i = 0; i < buttons.length; i++) {

        a = buttons[i].parentElement
        buttons[i].addEventListener('click', function () {
            console.log("test");
            a.parentElement.remove();
        });

    };
};
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Book store</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
<div class="container">
    <h1 class="title">Ajouter un livre</h1>

    <label for="titre">Titre:</label>
    <input type="text" name="titre" id="titre">

    <label for="Auteur">Auteur:</label>
    <input type="text" name="Auteur" id="auteur">

    <label for="Année">Année:</label>
    <input type="text" name="Année" id="année">

    <input type="submit" value="Ajouter" onclick="ajouter()">
</div>

<div class="table-container">
    <table id="myTable">
        <tr>
          
          <th>Titre</th>
          <th>Auteur </th>
          <th>Année</th>
        </tr>
        
      
      </table>
</div>

<script src="javascript.js"></script>
</body>
</html>


Solution 1:[1]

In your script you attach the click event handler only once to the already existing "delete" button(s):

if (ajouter() == false) {
    buttons = document.getElementsByTagName('button');
    ...
    for (i = 0; i < buttons.length; i++) {
        ...
        buttons[i].addEventListener('click', function () { ... })
        });
    };
};

All "delete"-buttons that are created later by your "ajouter" function will not have a click-event-handler attached to them.

Maybe the following is more what you want? In my snippet I applied the DRY (do not repeat yourself) rule vigorously:

  • First I declare a constant D as an object.
  • The object's properties are then defined as certain DOM elements, identified through their id attributes.
  • The "ajouter" click-event-handler-function is then directly assigned to the onclick event of the ajouter button
  • Inside the function a new DOM element tr is created, filled with content from the three input fields and append()ed to the <tbody id="tbd"> element (D.tbd).
  • The "delete" buttons are created as simple <button>s.

Outside the "ajouter" function a delegated click event is assigned to D.tbd. This will only result in action, if the clicked element's Tag name (ev.target.tagName) was "BUTTON". Then it's .closest("tr") parent element is searched and .remove()d.

const D={}; // global constant
["auteur","titre","annee","ajouter","tbd"].forEach(e=>
 D[e]=document.getElementById(e));

D.ajouter.onclick=()=>{
 const tr = document.createElement("tr");
 tr.innerHTML=`<td>${D.titre.value}</td>
  <td>${D.auteur.value}</td><td>${D.annee.value}</td>
  <td><button>delete</button></td>`;
 D.tbd.append(tr);
}

D.tbd.onclick=ev=>{
 if(ev.target.tagName==="BUTTON")
  ev.target.closest("tr").remove();
}
<div class="container">
 <h1 class="title">Ajouter un livre</h1>
 <label for="titre">Titre:</label>
 <input type="text" name="titre" id="titre"><be>
 <label for="Auteur">Auteur:</label>
 <input type="text" name="Auteur" id="auteur"></br>
 <label for="Année">Année:</label>
 <input type="text" name="Année" id="annee">&nbsp;<button id="ajouter">Ajouter</button>
</div>

<div class="table-container">
 <table><thead>
  <tr><th>Titre</th><th>Auteur </th><th>Année</th></tr>
  </thead><tbody id="tbd"><tbody>
 </table>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1