javascript - 当兄弟存在时,为什么 nextElementSibling 和 nextSibling 为 null?

标签 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

最佳答案

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

因此,

t2.firstChild 指的是 t2 内的文本节点,它是其唯一的子节点。独生子女没有 sibling 。

您可能想看看 t2 本身:

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

关于javascript - 当兄弟存在时,为什么 nextElementSibling 和 nextSibling 为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25188262/

相关文章:

javascript - MeteorJS 检查模板实例是否有 DOM

javascript - 在 Javascript 中访问所有事件监听器

javascript - 如何在 AngularJS 或 Ionic 上处理特定的路由状态 url 参数?如何对特定参数进行路由状态覆盖?

javascript - 使用切片从数组中删除元素

html - 想要使用 Bootstrap 将一个完整页面拆分为四个相同大小的 div

html - 我怎样才能将我的图像设置在右边?

javascript - 以编程方式插入新内容后重新运行 JQuery 的选择器和操作

javascript - 如何在 jQuery 事件处理程序中存储和重用超时?

html - 标题下方的 slider 在 ionic 3 中没有任何空格

javascript - SCRIPT5007 无法获取属性 'indexOf' 的值