It appears that the function is unable to delete the Node
containing the specified value unless it is the first value (such as 'apples'). Additionally, the for loop needs to run twice before any deletion occurs. What could be causing this behavior?
function removeSpec()
{
var query = document.getElementById('spec').value; /* User input value */
elements = document.getElementsByClassName('fruit'); /* Get the li elements in the list */
var myList = document.getElementById("myList3"); /* Reference to the list */
var length = (document.getElementsByClassName('fruit').length); /* Number of li elements */
var checker = 'false'; /* Boolean variable to track if value was found */
for(var counter = 0; counter < length; counter ++)
{
if (elements[counter].textContent == query )
{
alert("Counter : " + counter);
myList.removeChild(myList.childNodes[ (counter) ]);
checker="true";
}
}
if (checker == "false")
{
alert("Not Found");
}
}
The corresponding HTML:
<ul id="myList3">
<li class="fruit" >Apples</li>
<li class="fruit" >Oranges</li>
<li class="fruit" >Banannas</li>
<li class="fruit">Strawberry</li>
</ul>
<form>
Value: <input type="text" name="" value="" id="spec">
<br><br>
</form>
<button type="button" style="height:20px;width:200px" href="javascript:void(0)" onclick="removeSpec()" >
Remove Specified
</button>