Pieter Van der Haegen
Pieter Van der Haegen

Reputation: 357

javascript replaceChild doesn't work

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:

  1. Number one: Looking For a Mate
  2. Number two: Boredom
  3. Number three: Lack of Obedience
  4. Number four: Mistreatment
  5. Number five: Seeking Companionship

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:

  1. Number one: Looking For a Mate
  2. Number two: Boredom
  3. Number four: Mistreatment
  4. Number four: Mistreatment
  5. Number five: Seeking Companionship

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:

  1. Number one: Looking For a Mate
  2. Number two: Boredom
  3. Number three: Lack of Obedience
  4. Number four: Mistreatment
  5. Number four: Mistreatment
  6. Number five: Seeking Companionship

My teacher doesn't get why it won't work and me neither, can someone please help me?

Upvotes: 6

Views: 619

Answers (2)

T.J. Crowder
T.J. Crowder

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

dfsq
dfsq

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

Related Questions