How to Delete a Row in JavaScript Using an ID?

Estimated read time 2 min read

To delete a row in JavaScript using an ID, you can use the querySelector() method to select the row based on its ID. Once you have a reference to the row, you can use the deleteRow() method to remove it from the table.

Here’s an example of how to delete a row from a table with an ID of my-table and a row ID of row-1:

// Get a reference to the row you want to delete
var row = document.querySelector("#my-table #row-1");

// Get a reference to the table
var table = row.parentNode;

// Delete the row

In this example, we’re using a CSS selector to find the row with an ID of row-1 within the table with an ID of my-table. The querySelector() method returns the first element that matches the selector. Once we have a reference to the row, we can use its parentNode property to get a reference to the table element.

Finally, we can call the deleteRow() method on the table element to remove the row. The rowIndex property of the row element gives us the index of the row within the table.

Note that if the row you’re trying to delete is not found, the querySelector() method will return null, which will cause an error when you try to access its properties. You should always check that the row exists before trying to delete it.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply