Search code examples
javascriptfunctionhtml-table

Remove dynamically created row in table in js


I am using Otree live methods to implement a game with two roles: sellers send offers, which buyers can accept. I implemented this with a container and a container that adds clickable table rows:

<div class="container">
<h2> Job offers </h2>
<table class="table">
    <tbody id="offers_table">
    </tbody>
</table>
</div>

function liveRecv(data) {
    let current_offer = data["offer"];
    let player_offer = data["from"];
    let requested_effort = data["effort"];
    document.getElementById("offers_table").innerHTML +=
        `<tr><td> 
            Player ${player_offer} offered ${current_offer} for ${requested_effort} effort
            <button class="button" onclick="acceptOffer()"> Accept </button>          
        </td></tr>`;
}

Now I need to define the acceptOffer() function which should remove the row from the table which the person clicked (there are other players). In principle I can use similar code as above with -= but how can I reference the newly created element?


Solution

  • You need to pass "this" - a pointer to the button, as a parameter to the acceptOffer() function

     <button class="button" onclick="acceptOffer(this)"> Accept </button>
    

    Further, in the function itself, through the method .parentNode go to the row and remove it

    function acceptOffer(el) {
      const offer = document.querySelector("#offers_table");
      offer.removeChild(el.parentNode.parentNode);
      return false;
    }
    

    or else you can do this

    function acceptOffer(el) {
      el.parentNode.parentNode.parentNode.removeChild(el.parentNode.parentNode);
      return false;
    }
    

    PS: the first one .parentNode is a cell. the second .parentNode is a row. And third .parentNode is respectively tbody