当兄弟姐妹存在时,为什么nextElementSibling和nextSibling为null?

时间:2014-08-07 17:04:48

标签: javascript html dom

在这个HTML结构中:

<table id="outside">
  <tr>
    <td id="t1">one</td>
    <td>a</td>
  </tr>
  <tr>
    <td id="t2">two</td>
    <td>b</td>
  </tr>
</table>

为什么以下脚本:

// Function to change the content of t2
function modifyText() {
  var t2 = document.getElementById("t2");
  console.dir(t2.firstChild.nextElementSibling);
  console.dir(t2.firstChild.nextSibling);
  if (t2.firstChild.nodeValue == "three") {
    t2.firstChild.nodeValue = "two";
  } else {
    t2.firstChild.nodeValue = "three";
  }
}

// add event listener to table
var el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);

为什么nextElementSiblingnextSibling具有空值。我希望它们是兄弟td标签。

JSBIN

1 个答案:

答案 0 :(得分:2)

t2是指td#t2,因为ID为&#34; t2&#34;是td元素本身。

因此,

t2.firstChild指的是t2内的文本节点,它是唯一的子节点。独生子女没有兄弟姐妹。

您可能想要查看t2本身:

var t2 = document.getElementById("t2");
console.log(t2.nextElementSibling);
console.log(t2.nextSibling);