Home > other >  function that removes last element from table
function that removes last element from table

Time:11-22

I have this code that adds input to table. I want to make a function that removes the last added row in the table.
Here is the code that I have:

function add() {
  var name = document.getElementById("name");
  var surname = document.getElementById("surname");
  var output = document.getElementById("output");
  name = name.value;
  surname = surname.value;
  output.innerHTML  = "<tr><td>"   name   "</td><td>"   surname   "</td></tr>"
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial- scale=1.0">
  <title>Document</title>
  <style>
    table,
    td {
      border: 1px solid black;
      border-collapse: collapse;
    }
  </style>
</head>

<body>

  <form action="">
    <div>
      <label for="name">Name</label>
      <input type="text" id="name">
    </div>
    <div>
      <label for="name">Surname</label>
      <input type="text" id="surname">
    </div>
  </form>
  <input type="button" onclick="add();" value="Add">
  <input type="button" onclick="remove();" value="Remove">
  <div>
    <table id="output">
      <thead>
        <td>Name</td>
        <td>Surname</td>
      </thead>
      <tbody></tbody>
    </table>
  </div>


</body>

</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

For example if I enter more rows in my table and if I click on my remove button it will remove the last element that was entered in the table.

CodePudding user response:

Use .lastElementChild property to remove the last added tr tag in the table

function add() {
  var name = document.getElementById("name");
  var surname = document.getElementById("surname");
  var output = document.getElementById("output");
  name = name.value;
  surname = surname.value;
  output.innerHTML  = "<tr><td>"   name   "</td><td>"   surname   "</td></tr>"
}

function remove() {
  var output = document.getElementById("output");
output.lastElementChild.remove();
}
table,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
<form action="">
  <div>
    <label for="name">Name</label>
    <input type="text" id="name">
  </div>
  <div>
    <label for="name">Surname</label>
    <input type="text" id="surname">
  </div>
</form>
<input type="button" onclick="add();" value="Add">
<input type="button" onclick="remove();" value="Remove">
<div>
  <table id="output">
    <thead>
      <td>Name</td>
      <td>Surname</td>
    </thead>
    <tbody></tbody>
  </table>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related