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&g开发者_StackOverflow中文版t;
</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 have the dom element in javascript, you can use .parentNode() which will give you the parent node, which should be the table row. Then you can set .className
If you can use jQuery it could be something like this
$("yourtdselector").closest("tr").attr("class","classname");
For your code
<tr>
<td onclick="changeClass(this,'classname')">My TD</td>
</tr>
function changeClass(elem, class)
{
elem.parentNode.className = class;
}
jQuery is probably the easiest way of doing this, you can use selectors such as:
$('table.mytable tr').addClass('red');
To add a class of 'red' to all tr's in table.mytable. That's just the tip of the iceberg - check it out it should do what you need.
Without any extra framework:
document.getElementById("theTableName").rows[1].cells[1].className = "someclassname";
精彩评论