Change the content inside the <td> with the help of id of <tr>
How can I get the second child node of a tr
, which has 3 td
in it?
I have a code
rows=document.getElementById('mytr');
rows.firstChild.innerHTML='ddsds';
rows.lastChild.innerHTML='dd';
Now I would like to change the content in the middile also. how can I do that?
rows.secondChild.innerHTML='dds开发者_开发问答ds';
will not work.
Although I'd recommend using something like jQuery for this kind of manipulation, this is what you want:
var rows = document.getElementById('mytr');
var cells = table.getElementsByTagName('td');
cells[0].innerHTML = 'ddsds';
cells[1].innerHTML = 'ddsds';
cells[2].innerHTML = 'dd';
Access the childNodes or cells as array
rows.childNodes[1].innerHTML would do the second cell, as would
rows.cells[1].innerHTML
you can also use nextSibling,
rows.firstChild.nextSibling.innerHTML='ddsds';
and be careful while accessing child, these can return a text node if there are some white spaces. always try to validate if the child is not a text node using
rows.firstChild.nodeType == 1
// this will check if the node is not a text node
You can use .childNodes to find childnode by it's index.
rows.childNodes[1].innerHTML = 'foo'; // set foo to second child
if (rows.childNodes.length > 0)
rows.childNodes[1].innerHTML = "ddsds";
精彩评论