Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript replaceChild doesn't work

Tags:

javascript

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?

like image 621
Pieter Van der Haegen Avatar asked Dec 15 '14 10:12

Pieter Van der Haegen


2 Answers

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.

like image 183
T.J. Crowder Avatar answered Oct 24 '22 03:10

T.J. Crowder


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]);
like image 26
dfsq Avatar answered Oct 24 '22 03:10

dfsq