Reputation: 357
I'm a student of Computer science and we are making exercises on javascript the exercises was: "Replace item number 4 by a new item with id "numberFour" and with text "Mistreatment"." this is how it looked before i made the exercise:
then i wrote this js code to complete the assignment:
var vier = document.createElement("li");
vier.innerHTML = "Number four: Mistreatment";
vier.setAttribute("id", "numberFour");
var lijst = document.querySelector("#fiveReasons");
lijst.replaceChild(vier, lijst.childNodes[3]);
and then it looked like this:
so i changed this my code to this:
var vier = document.createElement("li");
vier.innerHTML = "Number four: Mistreatment";
vier.setAttribute("id", "numberFour");
var lijst = document.querySelector("#fiveReasons");
lijst.replaceChild(vier, lijst.childNodes[4]);
and then i got this:
My teacher doesn't get why it won't work and me neither, can someone please help me?
Upvotes: 6
Views: 619
Reputation: 1074555
childNodes
includes text nodes for whitespace between your li
elements (and comment nodes if any, etc.). Use children
if you want just child elements:
var vier = document.createElement("li");
vier.innerHTML = "Number four: Mistreatment - updated";
vier.setAttribute("id", "numberFour");
var lijst = document.querySelector("#fiveReasons");
lijst.replaceChild(vier, lijst.children[3]);
<ol id="fiveReasons">
<li>Number one: Looking For a Mate</li>
<li>Number two: Boredom</li>
<li>Number three: Lack of Obedience</li>
<li>Number four: Mistreatment</li>
<li>Number five: Seeking Companionship</li>
</ol>
children
works on all modern browsers, and IE8.
Upvotes: 5
Reputation: 193271
The problem is that childNodes
collection also includes text nodes (white spaces, line breaks, tabs, etc.), so they are also counted. Try children
instead:
lijst.replaceChild(vier, lijst.children[3]);
Upvotes: 4