Home > Software design >  Remove dynamically created row in table in js
Remove dynamically created row in table in js

Time:01-11

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 >
<h2> Job offers </h2>
<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  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?

CodePudding user response:

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

 <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

  • Related