简体   繁体   中英

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='ddsds'; 

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

您可以使用.childNodes通过索引来查找childnode。

rows.childNodes[1].innerHTML = 'foo'; // set foo to second child
if (rows.childNodes.length > 0)
    rows.childNodes[1].innerHTML = "ddsds";

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