代码之家  ›  专栏  ›  技术社区  ›  1252748

当兄弟存在时,为什么nextElementSibling和nextSibling为空?

  •  2
  • 1252748  · 技术社区  · 10 年前

    在此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);
    

    为什么 nextElementSibling nextSibling 具有空值。我希望他们是兄弟姐妹 td 标签。

    JSBIN

    1 回复  |  直到 10 年前
        1
  •  4
  •   BoltClock    10 年前

    t2 指的是 td#t2 ,因为ID为“t2”的元素是 td 元素本身。

    t2.firstChild ,因此,指内部的文本节点 时间2 ,这是它唯一的孩子。独生子女没有兄弟姐妹。

    你可能想看看 时间2 本身:

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