最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why are nextElementSibling and nextSibling null when sibling exists? - Stack Overflow

programmeradmin5浏览0评论

In this HTML structure:

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

Why does the following script:

// 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);

why do nextElementSibling and nextSibling have null values. I would expect them to be the sibling td tags.

JSBIN

In this HTML structure:

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

Why does the following script:

// 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);

why do nextElementSibling and nextSibling have null values. I would expect them to be the sibling td tags.

JSBIN

Share Improve this question asked Aug 7, 2014 at 17:04 12527481252748 15.4k34 gold badges117 silver badges242 bronze badges 5
  • 3 I don't see any references to nextElementSibling or nextSibling in your code. – BoltClock Commented Aug 7, 2014 at 17:05
  • @BoltClock You can see them in the console where t2.firstChild is printed. – 1252748 Commented Aug 7, 2014 at 17:06
  • Oh OK. So we're looking at those properties for t2.firstChild. – BoltClock Commented Aug 7, 2014 at 17:07
  • 2 you´re consoling the firstchild, and that doesn´t have siblings, the "td" does, but not the text node inside td – Sebastian Uriel Murawczik Commented Aug 7, 2014 at 17:07
  • 1 @SebastianUrielMurawczik so obvious now. Thanks much – 1252748 Commented Aug 7, 2014 at 17:08
Add a ment  | 

1 Answer 1

Reset to default 4

t2 refers to td#t2, since the element with the ID "t2" is the td element itself.

t2.firstChild, therefore, refers to the text node inside t2, which is its only child. An only child does not have any siblings.

You probably meant to look at t2 itself instead:

var t2 = document.getElementById("t2");
console.log(t2.nextElementSibling);
console.log(t2.nextSibling);
发布评论

评论列表(0)

  1. 暂无评论