通过 id 获取元素并更改其兄弟值
Get element by id and change its sibling value
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"
同级值?
这是因为,td
的下一个兄弟节点可能是文本节点,您需要下一个元素兄弟节点。
您可以使用 nextElementSibling 属性
document.getElementById("a").nextElementSibling.innerHTML = "newB";
<table>
<tr id="1">
<td id="a">aa</td>
<td>bb</td>
</tr>
</table>
注意:在 IE 9+
中支持
使用nextElementSibling
document.getElementById("a").nextElementSibling.innerHTML = "newB";
nextSibling
将 select 空 textNode
正如你在下面的演示中看到的那样
console.log(document.getElementById("a").nextSibling);
<table>
<tr id="1">
<td id="a">aa</td>
<td>bb</td>
</tr>
</table>
您可以看到,当元素之间没有 space 时,nextSibling
将按预期工作。所以,它不会 select 空 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>
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"
同级值?
这是因为,td
的下一个兄弟节点可能是文本节点,您需要下一个元素兄弟节点。
您可以使用 nextElementSibling 属性
document.getElementById("a").nextElementSibling.innerHTML = "newB";
<table>
<tr id="1">
<td id="a">aa</td>
<td>bb</td>
</tr>
</table>
注意:在 IE 9+
中支持使用nextElementSibling
document.getElementById("a").nextElementSibling.innerHTML = "newB";
nextSibling
将 select 空 textNode
正如你在下面的演示中看到的那样
console.log(document.getElementById("a").nextSibling);
<table>
<tr id="1">
<td id="a">aa</td>
<td>bb</td>
</tr>
</table>
您可以看到,当元素之间没有 space 时,nextSibling
将按预期工作。所以,它不会 select 空 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>