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?
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>
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With