user9273032
user9273032

Reputation:

Javascript Get the text in a particular table cell in (this) row

I have a table that's created dynamically. Each row have a button.

When I let on the button on a row I want it to get the text in a particular cell.

Something like this:

I have a table like this:

<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 do this using pure javascript or typescript?

Upvotes: 1

Views: 2067

Answers (2)

James
James

Reputation: 22247

In your setup for the getData function, this will refer to the button that was clicked - buttons don't have a "cell" property.

I would suggest:

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

then

function getData(btn) {
  var tr = btn.parentNode.parentNode; // the parent of btn is the td, the parent of td is the tr.
  var td = tr.getElementsByTagName("td")[0]; // get the first TD in the TR
  console.log(td.innerHTML); // log the content of the TD
}

Upvotes: 0

Scath
Scath

Reputation: 3824

I think you are trying to get the first cells text to do that you can use parentNode/childNodes to get a list of all the tds in the row and then pick the one you want by the index.

function getData(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="getData(this)">Get Data</button></td>
    </tr>
</table>

Upvotes: 2

Related Questions