Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript access TR from TD

I have a table row, and within that, I have a td (whatever it stands for). I would like to change the class attribute of the TR my TD is in without using an ID or a name. Like that:

<tr>
    <td onclick="[TR].setAttribute('class', 'newName')">My TD</td>
</tr>

How do I do it?

like image 393
arik Avatar asked Mar 26 '10 15:03

arik


2 Answers

td stands for table data..

now .. in your case you need the parentNode property of the td ..

<tr>
<td onclick="this.parentNode.setAttribute('class', 'newName')">My TD</td>
</tr>

or as bobince suggested in his comment

<td onclick="this.parentNode.className= 'newName'">My TD</td>
like image 70
Gabriele Petrioli Avatar answered Oct 02 '22 10:10

Gabriele Petrioli


In jquery, it would be really simple if you have the reference to your td:

$(this).closest('tr');

If you really don't want to take a dependency on jQuery, then you could just do a loop getting the parentNode and checking it's type as a more general purpose solution. In this case you could just get the parentNode since tr is always a direct parent of td. You can do something like this (note this was not tested):

var parent = myTd.parentNode;
while(true) {
  if(parent == null) {
    return;
  }
  if(parent.nodeName === "TR") {
    return parent;
  }
  parent = parent.parentNode;
}
like image 32
Keith Rousseau Avatar answered Oct 02 '22 09:10

Keith Rousseau