Navigating through the Document Object Model within a table

I'm working with an HTML table that contains a delete button in each row's last column. When the button is clicked, I want to delete the entire row. However, my current code only deletes the button itself and not the entire row:

var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener("click", function() {
    this.parentNode.parentNode.removeChild(this);    
  });
}

This is how my HTML structure looks like:

<body>
  <table class="table">
    <thead>
     <tr>
        <th>Students</th>
     </tr>
     <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th>Delete</th>
    </tr>
  </thead>   
  <tbody>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771d181f1937131812590204">[email protected]</a></td>
      <td><button>X</button></td>
    </tr> 

    <tr>
      <td>John</td>
      <td>Doe</td>
      <td><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6bcb9beb896b2b9b3f8a3a5">[email protected]</a></td>
      <td><button>X</button></td>
    </tr> 
</tbody>
</table>

Answer №1

It seems like the issue lies with the removeChild(this) method. This is called on the <tr>, but it's trying to delete the this element, which is actually the button.

You can try using this code instead:

var row = this.parentNode.parentNode;
row.parentNode.removeChild(row);

If you prefer using a framework like jQuery, the solution would be even simpler:

$(this).parent().parent().remove();

Update

The jQuery code provided above is concise and effective:

$(document).ready(function(){
    $('button').click(function(){
        $(this).parents('tr').remove();
    });
});

Answer №2

To remove a row from an HTML table, you can utilize the HTMLTableElement.deleteRow() method. Each button in the table has been assigned an onclick event that triggers the deleteRow function, leveraging the rowIndex property and deleteRow() method for deletion. This functionality does not rely on jQuery for implementation.

Sample HTML:

<table class="table" id="table">
    <thead>
     <tr>
        <th>Students</th>
     </tr>
     <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th>Delete</th>
    </tr>
  </thead>   
  <tbody>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="640e0b0c0a24000b014a1117">[email protected]</a></td>
      <td><button onclick="deleteRow(this)">X</button></td>
    </tr> 

    <tr>
      <td>John</td>
      <td>Doe</td>
      <td><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d676265633c4d69626823787e">[email protected]</a></td>
      <td><button onclick="deleteRow(this)">X</button></td>
    </tr> 
</tbody>
</table>

JS snippet:

function deleteRow(r) {
    var i = r.parentNode.parentNode.rowIndex;
    document.getElementById("table").deleteRow(i);
}

Check out the live demo here!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on retrieving HTML content from a URL and showing it in a div

I'm trying to retrieve the content of a URL and display it within a DIV element, but I'm struggling to achieve the desired result. Below is the code I'm using: index.js fetch('https://github.com/') .then(res => res.text()) ...

What is the best way to animate the preprending of a div in an AJAX response?

Here is the code I am currently working with: $.ajax({ type: 'POST', url: 'load_more.php', data: {val:myval}, success: function (data) { $("#load_current").prepend(data); ...

What is the reason that prototypes are not passed down through inheritance?

Can anyone shed light on why Validator.js is structured the way it is initialized (as shown in the first code snippet) and the reason behind the inability to call the validate method (as demonstrated in the second snippet)? I am currently experimenting wi ...

My React application came to an unexpected halt with an error message stating: "TypeError: Cannot read properties of undefined (reading 'prototype')"

Everything was running smoothly with my app until I encountered this error without making any significant changes: TypeError: Cannot read properties of undefined (reading 'prototype') (anonymous function) .../client/node_modules/express/lib/resp ...

When downloading files in Chrome or Safari, the $ajax call is in a pending state, whereas in IE or Firefox,

Measuring the time it takes to download a 1MB file using AJAX calls. Below is the code snippet: var start = new Date(); $(document).ready(function() { $.ajax ({ url: 'https://www.example.com/dummyFile1024', crossDomain: t ...

Press the button located within the canvas element

How can I click on the verify button embedded inside a canvas element using either jQuery or Selenium? Please advise me on how to successfully click inside the canvas. ...

Delaying the call of a JavaScript function with jQuery

Basic JavaScript Function: $(document).ready(function(){ function sampleFunction() { alert("This is a sample function"); } $("#button").click(function(){ t = setTimeout("sampleFunction()",2000); }); }); HTML ...

Verifying the name's uniqueness and disregarding it in case of any alterations

I am currently working on a form that includes a modal to allow users to modify their name and email address. The issue I am facing is that the form sends a request to the server to check for unique values in all cases. While this is appropriate when creat ...

Is it possible to resize an object using JavaScript?

Is it possible to change the size of an object when loading specific data by clicking on navigation? <object id="box" width="250" height="250" data=""></object> Although the JS code loads the data, it does not change the size. document.getEl ...

Add middleware to one individual store

When working with Redux, it is possible to create middleware that can be easily applied to the entire store. For example, I have a middleware function called socketMiddleware that connects to a socket and dispatches an action when connected. function sock ...

Having trouble getting datatables.net to function properly with JavaScript

I've been experimenting with datatables from http://datatables.net/ Attempting to make it work using javascript, but I'm facing issues. Even when following the example provided on the website, it still shows a blank page. Does anyone have any su ...

Dynamically hiding elements within tabs using jQuery

Previously, I created a functionality for handling a single set of tabs. However, as the application has expanded, this functionality is no longer sufficient to accommodate multiple sets of tabs. The initial function looked like this: var iconTabs = func ...

The getInitialProps function in Next.js is not functioning properly in mobile browser environments

My app runs perfectly on desktop without any errors. However, when I switch to a mobile device, I noticed that the pages fail to trigger the getInitialProps method on the client side, only if I navigate through the Link component. This is my code: return( ...

Error message: Attempting to access a property that is undefined (specifically 'ref') in MUI

Has anyone encountered this error when trying to customize themes in MUI v5 using custom variants? I keep seeing this error message: TypeError: Cannot read properties of undefined (reading 'ref') at Select (/var/www/miniatureawards.com/node_ ...

Sending properties through the React Router to a specific component

Within my component, I have a material table that triggers a function when the edit button is clicked: //MaterialTable.js ... const handleEdit = (e, Data) => { console.log(Data) return(<EditFunction id={Data.id} />) ... The purpose of ...

Getting a JWT token from Express to Angular using ngResource: A step-by-step guide

Currently, I am utilizing a jwt token for user registration validation. A unique URL is generated and sent to the user via email, which leads them to the authentication page. On the server side, the token is decoded and I need to transmit this JSON data to ...

Struggling with TypeScript errors due to React.HTMLProps for HTMLAnchorElement

When trying to extend a React component with React.HTMLProps without explicitly defining onClick in the attribute list, ESLint complains when passing onClick as an attribute while using the component. Here's an example of the code: The React componen ...

Issue with 1.bundle.js not loading during webpack production build with routing

I have been encountering an issue with my test repository for this specific problem (Link) It appears that the problem lies within the localization file, as I am using react-intl. The development version seems to be functioning properly. This is what&ap ...

Troubleshooting Google Charts, AJAX, and PHP: Issue with JSON encoding leading to error message "Data for arrayToDataTable is not

My current project involves using PHP/PDO/MSSQL to pass data from a database to a Google Chart via AJAX in .js. I'm encountering an issue that seems to be related to encoding. I've been following a tutorial at which hardcodes the data into the ...

Test your knowledge of Javascript with this innerHtml quiz and see

How can I display the output of a score from a three button radio button quiz without using an alert popup? I want the output to be displayed within a modal for a cleaner look. I tried using InnerHTML but now there is no output when the button is clicked. ...