Javascript replaceChild not working

I am a computer science student, and we do javascript exercises, the exercises were: "Replace element number 4 with a new element with the identifier" numberFour "and the text" Mipreatment "." this is how it looked before i did the exercise:

  • Number One: Finding an Assistant
  • Number Two: Boredom
  • Number Three: Lack of Obedience
  • Number Four: Mistreatment
  • Point Five: Search for Companions

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 he looked like this:

  • Number One: Finding an Assistant
  • Number Two: Boredom
  • Number Four: Mistreatment
  • Number Four: Mistreatment
  • Point Five: Search for Companions

so I changed this 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 the following:

  • Number One: Finding an Assistant
  • Number Two: Boredom
  • Number Three: Lack of Obedience
  • Number Four: Mistreatment
  • Number Four: Mistreatment
  • Point Five: Search for Companions

My teacher does not understand why this will not work, and I can’t, can someone help me?

+6
source share
2 answers

childNodes contains text nodes for spaces between your li elements (and comment nodes, if any, etc.). Use children if you want only children:

 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 in all modern browsers and IE8.

+5
source

The problem is that the childNodes collection also includes text nodes (spaces, line breaks, tabs, etc.), so they are also considered. Try children :

 lijst.replaceChild(vier, lijst.children[3]); 
+3
source

Source: https://habr.com/ru/post/979609/


All Articles