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?
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.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With