What is the best way to extract the initial td value from a tr using JavaScript?

<tr>
  <td>Sample Data</td>
  <td>2020</td>
  <td>75</td>
  <td>05-20-2018</td>
  <td><a href="#" class="delete-item secondary-content"><i class="fa fa-trash"></i></a></td>
 </tr>

In my table, there is a row with the data presented above. I would like to extract the first value in the row, which is "Sample Data", when the <i> element is clicked.

The rows are contained within a div with the ID of #list.

del(target,title) {
  if (target.className === 'fa fa-trash') {
    // To access and compare this title in LocalStorage for deletion purposes
  }
}

document.getElementById('list').addEventListener('click', function (e) {
  const tr = e.target.parentElement.parentElement.parentElement;
  console.log(tr);

  del(e.target, title);
});

The output displayed on the console will be:

<tr>
  <td>Sample Data</td>
  <td>2020</td>
  <td>75</td>
  <td>05-20-2018</td>
  <td><a href="#" class="delete-item secondary-content"><i class="fa fa-trash"></i></a></td>
</tr>

How can I locate the first <td> from this point without utilizing jQuery?

Answer №1

To make the click event more specific, consider targeting a particular element within the table instead of triggering on any click on the entire table.

You were on the right track with selecting the tr element. Once you have the tr, you can pass it into the del function and utilize getElementsByTagName on the tr to retrieve the first td from the tr.

After that, you can use removeChild to remove the first td that was queried from the parent node of the tr.

Here is an example:

function del(e){
    let firstTD = e.getElementsByTagName("td")[0];
    console.log(firstTD);
    e.removeChild(firstTD);
}

document.querySelectorAll('#list .fa').forEach(function(trash) {
  trash.addEventListener('click', function(e) {
    const tr = e.target.parentElement.parentElement.parentElement;
    del(tr);
  });

});
<div id="list">
  <table>
    <tbody>
      <tr>
        <td>Test Data</td>
        <td>2016</td>
        <td>59</td>
        <td>10-12-2014</td>
        <td><a href="#" class="delete-item secondary-content"><i class="fa fa-trash">trash</i></a></td>
      </tr>
      <tr>
        <td>Test Data 2</td>
        <td>2015</td>
        <td>33</td>
        <td>11-23-2012</td>
        <td><a href="#" class="delete-item secondary-content"><i class="fa fa-trash">trash</i></a></td>
      </tr>
    </tbody>
  </table>
</div>

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

What is the best way to efficiently query a substantial dataset using Node.js in an asynchronous fashion?

I need to extract data from a mysql database by fetching 10 rows at a time until I reach 400k rows. To achieve this asynchronously, I am using recursion as shown in the code below: var migrate = function(offset, size) { Mysql.query(query, [offset, size] ...

What steps should I take to ensure that pull is functioning correctly with mongoose and mongodb?

I am facing an issue while trying to retrieve an object from an array within a Model. Despite verifying my query params and confirming that they are correct, I am unable to get it to function as expected. Any assistance on this matter would be highly appre ...

What are the steps for integrating a CMS with my unique website design?

Currently, I am in the process of creating a unique website for a client using my own combination of html, css, and JavaScript. There is also a possibility that I may incorporate vueJS into the design. The client has expressed a desire to have the ability ...

JQuery Autocomplete Error: Unable to access property 'value' of undefined

I am currently utilizing a jquery autocomplete plugin found here. However, I am encountering an issue when I click on a filtered result, triggering the following error: Uncaught TypeError: Cannot read property 'value' of undefined Upon inspecti ...

Tips for resizing an image to perfectly fit on a compact HTML5 canvas without sacrificing its quality

I need assistance with my code. I'm trying to draw an image on the canvas while maintaining its quality. const canvas = document.getElementById("canvas"); const context = canvas.getContext("2d"); canvas.width = 360px; canvas.height = 360px; const img ...

Having trouble retrieving the DD-MM-YYYY date format in Vue.js from MySQL database

Hi, I am struggling with setting the format of dateCreated (the date when the account was created) to DD-MM-YYYY. In my Vue page, the code looks like this: https://i.sstatic.net/8SSAE.png The issue is that the website displays the date in the format sho ...

Are there any specific steps I should take to ensure that my server can support jQuery.getJSON when using a bookmarklet?

Currently, I am in the process of creating a bookmarklet that will require some user details to be input. After researching my options for cross domain communication, I have found that my best choices are either using jQuery.getJSON or adding a form and i ...

Eliminating bottom section in HTML/CSS

I've got this code snippet: new WOW().init(); /* AUTHOR LINK */ $('.about-me-img img, .authorWindowWrapper').hover(function() { $('.authorWindowWrapper').stop().fadeIn('fast').find('p').addClass('tr ...

Getting the iframe onload event in an ASP.NET application

I have integrated ReportViewer to display SSRS reports on my .aspx page. However, since the ReportViewer is rendered as an iframe in the browser, I am looking for a way to trigger a JavaScript function every time the iframe loads. Using window.onload w ...

Google Analytics Experiments implemented on the server-side

Curious about the necessity of including the JavaScript cxApi when conducting experiments server-side. Is it possible to send the selected experiment and variations using PHP, or perhaps by injecting a JavaScript snippet internally (without relying on exte ...

Three.js: "Identifying Tool" How to recognize the overlap between a 2D square and 3D elements

I am looking to achieve the following: I have a 3D map with objects, and I need to select all objects that fall within a specific 2D box defined by coordinates x1,y1 and x2,y2 on my screen. I am unsure of how to approach this task and would appreciate an ...

I'm having trouble customizing the appearance of a Tab Panel using the TabsAPI. The panel keeps expanding in strange ways. How can I

Trying to customize the Tabs component from MUI is proving to be a challenge. The main issue I am facing currently is: Whenever I switch between tabs, they appear to expand in size mysteriously. This behavior seems to occur only on tabs with more content ...

Adjusting the alignment of the horizontal bars in react-chartjs-2

I have configured the graph with the following settings: { type: 'horizontalBar', indexAxis: 'y', barThickness: 12, scales: { x: { suggestedMax: 6, suggestedMin: 0, grid: { display ...

Transform unicode characters into HTML code

Within my application, I need to display scientific units such as m³/h. To achieve this, I store the Unicode representation in my database as m\u00b3/h. However, when retrieving data from the API, it includes an extra backslash like "sign": ...

Dragging elements using the jQuery UI Draggable feature onto a designated droppable area

Struggling to implement a Draggable element on Droppable element using jQuery UI? I almost got it working, but the elements on the droppable area keep changing their positions when moved slightly. I want them to stay put, but return to their original place ...

JavaScript / html Error: function body missing closing curly brace

I encountered an error that I'm struggling to resolve: "SyntaxError: missing } after function body". Despite not having a function named 'body', I have attempted changing every instance of 'body' in my script. However, ...

What are some ways to direct users from one page to another without relying on server-side programming?

Is there a way to create a redirect page using jQuery or JavaScript? What is the process of writing client-side scripting code to redirect the browser from one page (page1) to another page (page n)? ...

What is the best way to set a checkbox's default state in a react table using a value from Firestore?

Is there a way to initialize the checkboxes in React Table based on values from Firestore? I've tried reading the official documentation and looking at some examples, but I'm still confused about how to achieve this. My goal is to retrieve a val ...

Is there a way to render the hidden faces of the cube to the framebuffer? (The sides that are not visible from my current perspective)

I am currently working on implementing volume rendering in WebGL using the Three.js library. While I have experience with pure WebGL, I'm facing challenges finding a similar approach in Three.js. Here are the issues at hand: 1) How can I render the ...

Prevent duplicate rectangles by cleaning up dirty rectangles

I'm looking to optimize the performance of my game by only clearing the necessary parts of the canvas that contain animations. Below is a snippet of my code: this.draw = function(context) { context.clearRect(this.oldx, this.oldy, this.width, ...