How can I remove a specific Li tag based on its order number via text?

Viewed 100

I have been trying to figure out how I can remove a specific "li" tag by typing in its number based on its position in a list (i.e. type 3 in text box, then press a button to delete item in position 3 of the list). The way my code is now, even if there are only 4 items listed, typing in 5 and hitting enter still deletes 2 items rather than not deleting any. The way my code is written, it is not being consistent with the number being typed to delete the specific "li" tag.

Any help would be appreciated, thank you.

<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="rfruit" id="fruitremove">
  <input type="button" value="Click to Remove" onclick="removefruit()">
  Remove fruit you dislike
</form>


<script type="text/javascript">


function removefruit(){
  var fruitminus = document.getElementById("fruitremove").value;
  var flist = document.getElementById("fruit");


  flist.removeChild(flist.childNodes[fruitminus]);

}

</script>

</body>
</html>

1 Answers

The problem arises because the NodeList created for your flist has a length of 8 in your case. This is because 2 elements are created per list element (one is a text and one is li). So, simply add an if condition before removing the childnode like this:

if(fruitminus < (flist.childNodes.length)/2)
    flist.removeChild(flist.childNodes[2*fruitminus - 1]);

The index for li is present at odd positions in the NodeList which is why we need to remove the childNode at that position.

Related