按id获取元素并更改其兄弟值

时间:2015-09-16 04:21:09

标签: javascript siblings

HTML

<table>
    <tr id="1">
        <td id="a">aa</td>
        <td>bb</td>
    </tr>
</table>

的JavaScript

document.getElementById("1").children[1].innerHTML="newB"  // it works as expected.     
document.getElementById("a").nextSibling.innerHTML="newB" // it does not work.

如何使用第二种方法更改td id="a"兄弟值?

2 个答案:

答案 0 :(得分:1)

使用nextElementSibling

document.getElementById("a").nextElementSibling.innerHTML = "newB";

nextSibling将选择空textNode,如以下演示

所示

console.log(document.getElementById("a").nextSibling);
<table>
  <tr id="1">
    <td id="a">aa</td>
    <td>bb</td>
  </tr>
</table>

当元素之间没有空格时,您可以看到nextSibling将按预期工作。因此,它不会选择空的 textNode

document.getElementById("a").nextSibling.innerHTML = "newB";
<table>
    <tr id="1">
        <td id="a">aa</td><td>bb</td> <!-- No space, it works! -->
    </tr>
</table>

答案 1 :(得分:0)

这是因为,td的下一个兄弟可能是一个文本节点,你需要下一个元素兄弟。

您可以使用nextElementSibling属性

document.getElementById("a").nextElementSibling.innerHTML = "newB";
<table>
  <tr id="1">
    <td id="a">aa</td>
    <td>bb</td>
  </tr>
</table>

注意:IE 9+

支持