Retrieve the content from a specific cell within the table in the current row using Javascript

I am working with a dynamically generated table where each row has a button.

My goal is to retrieve the text from a specific cell when the button in that particular row is clicked.

For example:

Here is an example of my table structure:

<table>
    <tr>
        <td>Test 1 Here</td>
        <td>Other Text Here</td>
        <td><button onclick="getData(this.cell[1].innerHtml)">Get Data</button></td>
    </tr>
</table>

How can I achieve this using either pure JavaScript or TypeScript?

Answer №1

To retrieve the text of the first cell in a row, you can utilize the parentNode/childNodes method to access all the tds in the row and then select the desired one based on its index.

function fetchData(x)
{
console.log(x.parentNode.parentNode.childNodes[1].innerHTML)
console.log(x.parentNode.parentNode.childNodes[3].innerHTML)
}
<table>
    <tr>
        <td>Test 1 Here</td>
        <td>Other Text Here</td>
        <td><button onclick="fetchData(this)">Get Data</button></td>
    </tr>
</table>

Answer №2

When setting up the getData function, keep in mind that this will represent the button that was clicked - buttons do not have a "cell" property.

One suggestion would be to use the following code:

<button onclick="getData(this)">Get Data</button>

After that, you can utilize the following function:

function getData(btn) {
  var tr = btn.parentNode.parentNode; // Obtain the parent of the button (TD), and then the parent of the TD (TR).
  var td = tr.getElementsByTagName("td")[0]; // Get the first TD element within the TR.
  console.log(td.innerHTML); // Display the content of the TD element.
}

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

A guide on invoking a function within a nested or local function

When the code below is executed in a local function, such as the one inside s3.getObject, it throws an error stating that setState is not a function. s3.getObject({ Bucket: bucket, Key: key }, function (error, data) { if (error != ...

Ionic - encountering crashes with ion-nav-view on emulator

I am encountering an issue with ion-nav-view. Whenever I try to use it, the emulator displays a black screen, but it works perfectly fine in ionic serve. I suspect it may be a syntax error causing this problem. Interestingly, when I create a blank projec ...

How can one elevate the properties of each item's sub-structure to the root level in an array containing object items?

I am working with an array containing objects, each with a specific structure... [{ user: { /* ... more (nested) user data ... */ }, vacation: { id: 'idValue', name: 'nameValue', startDate: 'dateValue', }, }, ...

Calculating the combined total and mean values within an object using JavaScript

I have a set of data in the following format: { "Dates": ["January", "January", "March", "March", "March", "November", "November"], "Values": [45.6, 0.5, 59.3, 46.56, ...

Fixing border prioritization in a table using the CSS style "border-collapse: collapse"

I have encountered a problem where certain borders take precedence over others when using the border-collapse: collapse styling in a table. Specifically, when setting the border-right on a cell, it appears above the border-left. Is there a way to adjust th ...

Utilizing Lodash debounce in VueJs watch feature while incorporating Typescript

When working with VueJS in Javascript, I can achieve the following: import debounce from "lodash/debounce"; ... watch: { variable: debounce(function() { console.log('wow'); }, 500) } However, when attempting to do the same in VueJS us ...

Why is my client-side code being compiled and executed on the Node.js backend?

As a newcomer to SSR, I'm not sure if my problem and solution align with standard practices, but it seems unlikely. My objective is to create a dynamic page that allows users to add/remove items. Initially, I developed this component for a client-sid ...

Is there a way to round a number in JavaScript with negative precision similar to the rounding function in Excel?

Is there a way to round the value 8904000 to 8900000 using Math.round? An example of this in MS Excel is shown below: =round(8904000,-5); ANS: 8900000 I attempted to use Math.round with a second argument, but it did not work as expected: Math.round(8904 ...

Challenge with module declaration in index.d.ts during upgrade from Angular 8 to 9 (excluding Material)

In my index.d.ts file, I have declared two modules like so: declare module 'googlemaps'; declare module 'detect-resize'; Previously, these declarations worked perfectly fine, allowing me to utilize these modules. The googlemaps module ...

An issue arising from code in Python, JavaScript, HTML, and CSS

I am currently studying JavaScript and Python and have encountered an issue with my code. I wrote a script that is supposed to create a file and input data into it, but the recv_data function is not functioning correctly - the file is not being created. Ca ...

Errors with pointer events occurring within nested iframes on Chromium 78

At first glance, it seems like a bug specific to Chromium. I have already reported this issue in a bug report. Since progress is slow on that front, I am posting a question here primarily to see if anyone else has encountered similar or related issues and ...

send the value from the input field to the designated button - link the two buttons

My goal is to create a feature where users can click on a button within the map and open an external page in Google Maps with specific dimensions (500 X 600) and without the Menu bar, Tool bar, or Status bar. // Custom Button Functionality by salahineo ...

Can someone please advise me on how to output the value of a var_dump for an array using console.log?

After writing the code in this manner, it functions properly and returns a JSON object. public function getElementsAction() { $currency = App::$app->getProperty('currency'); if(!empty($_POST)) { $sql = 'SELECT name, p ...

Nestjs is throwing an UnhandledPromiseRejectionWarning due to a TypeError saying that the function this.flushLogs is not recognized

Looking to dive into the world of microservices using kafka and nestjs, but encountering an error message like the one below: [Nest] 61226 - 07/18/2021, 12:12:16 PM [NestFactory] Starting Nest application... [Nest] 61226 - 07/18/2021, 12:12:16 PM [ ...

Does the array.sort() method behave in-place when used on Object.keys()?

When utilizing the .sort() method of JavaScript arrays, the array is altered directly and a reference to the array is returned. Object.keys(obj) generates an array with all the keys from object obj. It's important to note that in JavaScript, object ...

Utilizing TypeScript with Msal-React for Prop Type Validation

I'm currently implementing authentication in my app using msal-React. Within my app, I have a component that utilizes msalcontext and is wrapped by withMsal: function App(props: any) { return ( <> <AuthenticatedTemplate> ...

Issue with ThreeJS AdditiveBlending, ShaderMaterial, and DepthTest

As I work on creating a scene with a variety of objects, I drew inspiration from a CodePen example by gnauhca (https://codepen.io/gnauhca/pen/VzJXGG). In the example, DepthTest is disabled on the ShaderMaterial, but I actually need it to be enabled in orde ...

What are some solutions to correct a tab layout that is utilizing absolute positioning?

Although I understand how absolute positioning works, it is currently disrupting the layout in this particular case. Using min-height with media queries for various screen sizes seems like a viable solution, but it's not foolproof considering that the ...

What could be causing my POST route to be missing in my MERN stack application?

I'm encountering two issues with a MERN stack application: i) Despite the POST route working, Axios fails to send form body data to the server. MongoDB only displays default field values after each submission. ii) The POST route was operational init ...

HTML code now launches in the existing electron window rather than opening a new window

<html> <head> <title></title> </head> <input type="button" name="new" id="newmon" value="new"> <button onclick="open1()">monitor 1</button&g ...