Reputation: 15362
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.
Upvotes: 2
Views: 9929
Reputation: 723388
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);
Upvotes: 4