简体   繁体   中英

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?

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.

没有任何额外的框架:

document.getElementById("theTableName").rows[1].cells[1].className = "someclassname";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM