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
ornextSibling
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
1 Answer
Reset to default 4t2
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);