I recently had some help here on removing an li tag via text based on its position in this list. Now, when putting that script together with my entire code, it no longer works as intended. The goal is to able to add new li entries to my list (adding onto the 4 already in place) and then be able to delete the new entries via user input from the text box. The problem is that, say I add 3 new li tags, after this, I am unable to delete the correct li tag (i.e. if there are 5 elements, I type 5 to delete li tag 5, but nothing happens). I'm thinking after new li tags are added, they are not being recognized as part of the preset list.
<html>
<head>
<title>Chapter 5 Activity</title>
</head>
<body>
<h1>The Best Fruit in the World</h1>
<ol id="fruit">
<li>Mangos</li>
<li>Watermelons</li>
<li>Kiwis</li>
<li>Pineapples</li>
</ol>
<form action="">
<input type="text" name="afruit" id="fruitadd">
<input type="button" value="Click to Add" onclick="addfruit()">
Add your favorite fruit to the list<br>
<input type="text" name="rfruit" id="fruitremove">
<input type="button" value="Click to Remove" onclick="removefruit()">
Remove fruit you dislike
</form>
<script type="text/javascript">
function addfruit() {
var fruit1 = document.getElementById("fruitadd").value;
var newfruit = document.createElement("li");
newfruit.innerHTML = fruit1;
var flist = document.getElementById("fruit");
flist.insertBefore(newfruit, flist.childNodes [0]);
}
function removefruit(){
var fruitminus = document.getElementById("fruitremove").value;
var flist = document.getElementById("fruit");
if(fruitminus < (flist.childNodes.length)/2)
flist.removeChild(flist.childNodes[2*fruitminus-1]);
}
</script>
</body>
</html>
flist.childNodes contains in order [text, li, text, li, text, li, text, li, text]
so index 5 is actually a text node.
Here's a working function for removing an item base on index number.
function removefruit() {
var fruitminus = parseInt(document.getElementById("fruitremove").value);
var flist = document.getElementById("fruit");
flist.children[fruitminus - 1].remove();
}