简体   繁体   中英

Delete entire table row in vanilla Javascript

I have a HTML table (table2) that is dynamically populated with copies of rows (rowData) from another table (table1) when an 'add' button on table1 is clicked.

The table2 rows include a 'remove' button - so if the user clicks 'remove', I need to remove the entire row corresponding to that button.

So far, I have added an onclick attribute with the innerHTML, but I'm struggling to create a successful remove() function that deletes the clicked row!

addToFavourites(someData);

// someData will look like this:

// <tr class='resultRow'>
//  <td>text1</td>
//  <td>text2</td>
//   <td>text3</td>
// </tr> 

const addToFavourites = rowData => {
    let table2Row = document.createElement("tr");
    table2Row.innerHTML = 
`${rowData.innerHTML}<td class='cell'><button type='button' onclick='remove()' class='remove-btn'>Remove</button></td>
`;
    table2.appendChild(table2Row);
  }; 

First you need the delete button to reference something, like an ID or a class, or perhaps event.target.parentElement.... (assuming the button's event target is the button itself) and each row has its own button. Since you don't have unique IDs in your code, I'll attempt to make this work with what you have.

const remove = (event) => {
  // the first parentElement is <td>, then second is <tr>
  event.target.parentElement.parentElement.remove();
}

const addToFavourites = rowData => {
  let table2Row = document.createElement("tr");
  table2Row.innerHTML = `${rowData.innerHTML}<td class='cell'><button type='button' onclick='remove()' class='remove-btn'>Remove</button></td>`;
  table2.appendChild(table2Row);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM