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

Tips for optimizing the sequencing of 3 ajax requests, with the output of one request serving as input for the subsequent two requests

I'm currently working on a solution for chaining 3 ajax calls where the result of one call feeds into the next two. Here's the scenario: // Invoke the ajax calls firstAjax('mypage.gng','john-doe').then(secondAjax, thirdAjax) ...

What is the best way to utilize eslint in Vue components?

I'm facing an issue with my .vue file that defines a component. Other .vue files are unable to see it properly due to linter errors. I keep getting ES Lint errors like: Cannot find module '../components/LinkButton'. I have tried several st ...

Create a new class in the body tag using Javascript

If the operating system is MAC, I set a variable and then based on a condition, I want to add a new class in the body tag. Check out my code snippet: <script type="text/javascript" language="javascript"> var mac = 0; if(navigator.userAgent.index ...

AngularJS encountered an error: [$injector:modulerr] problem occurred during code execution

Hey there! I've been trying to set up a pop-up feature in Angular, but unfortunately, I keep encountering an error: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.9/$injector/modulerr?p0=PopupDemo&p1=Error%…ogleapis.com%2Fa ...

Creating a banner image that scrolls while maintaining a fixed size

I'm looking to add a banner image with a scrolling effect as users navigate down the page, but I'm not sure what this technique is called. An example of what I'm trying to achieve can be seen on this site. As the user scrolls down, the res ...

When trying to gather multiple parameters using @Param in a NestJS controller, the retrieved values turn out

Can someone help me understand why I am struggling to retrieve parameters using the @Param() decorators in my NestJS controller? These decorators are defined in both the @Controller() decorator argument and the @Get() argument. I am relatively new to Nest ...

Is there a way to sort search outcomes by a drop-down menu in Next.js?

I am currently working on implementing a filter for my data based on selections made in a drop-down menu. Here's the setup: I have MSSQL data being pulled into NextJS using Prisma (ORM). My goal is to create a dropdown filter that will refine the di ...

Strategies for handling numerous node projects efficiently?

Currently, we are utilizing three distinct node projects: Project 1, Project 2, and Project 3 incorporating react and webpack. Each of these projects is stored in their individual repositories. While Project 1 and Project 2 operate independently, Project ...

Is it possible to use TypeScript in a React Native project with a JavaScript file?

Currently, I am learning React Native by working on app clones like Instagram and YouTube. I have recently started an AirBnb clone project, but I'm facing some issues with the initial build. One issue I noticed is that in 'App.js', the temp ...

What is the procedure for matching paths containing /lang using the express middleware?

I need to target paths that contain /lang? in the URL, but I am unsure how to specifically target paths that begin with /lang? I have two routes: app.get('/lang?..... app.get('/bottle/lang?....... I want to target these routes using app.use(&a ...

Render a component in certain routes based on specific conditions in React

This is my Index.js ReactDOM.render( <React.StrictMode> <Provider store={store}> <Router> <App className="app-main" /> </Router> </Provider> </R ...

Automatically switch slides and pause the carousel after completing a loop using Bootstrap 5 Carousel

Seeking assistance with customizing the carousel functionality. There seems to be some issues, and I could use a hand in resolving them. Desired Carousel Functionality: Automatically start playing the carousel on page load, and once it reaches the end of ...

Above the search box in jQuery Datatable's search box, there is search text displayed

My datatable looks like this: var exTable1 = $("#exTable").DataTable({ "language": { "search": "Filter", "searchPlaceholder": "search", "loadingRecords": "", }, data: datasrc "dom": '<"top"lf>rt<"botto ...

"Integrating JavaScript in C# Code Behind: A Step-by-Step Guide

Is there a way to trigger this javascript function using C# code in the backend when the page loads? Your assistance is greatly appreciated, thank you. <script type="text/javascript"> document.onkeydown = function (event) { event = ( ...

Increasing the checkout date by one day: A step-by-step guide

I am looking to extend the checkout period by adding 1 more day, ensuring that the end date is always greater than the start date. Below are my custom codes for implementing the bootstrap datepicker: $(function() { $('#datetimepicker1').da ...

The issue of variable stagnation in Firefox content script while utilizing self.port.on

I'm having trouble updating the version var as intended. When I try to update it with the following code: self.port.on("get-version", ver => { version = ver; alert(version); }); An alert pops up displaying the correct version number, but the HTML ...

Ways to eliminate the blue selection box when dragging canvas objects in fabric framework

I've been trying to find a solution to remove the annoying blue highlight box that appears when dragging on the canvas while using fabric js, but so far I haven't had any luck. I've tried the following code, but it only works for text and n ...

Interval function not initiating properly post bullet navigation activation

Currently, I am experiencing an issue with my custom slider where the auto sliding set interval function is not working after using the bullet navigation. Despite trying to implement "setTimeout(autoSlide, 1000);", it doesn't seem to be resolving the ...

unique jquery plugin accesses function from external javascript file

As a beginner, I am attempting to create a custom jQuery plugin for which I have a simple HTML form: <form id="registerForm" action = "somepage" method="post" class="mb-sm"> <div class="form-group"> <div class="col-md-12"> ...

Ways to restrict the content div JSON display to only three items

Is it possible to limit the display of items from JSON in the content div to just three? The current code displays all downloaded items, but I want only 3 divs to be returned. <div id="p"></div> $.getJSON('element.json', function(d ...