i have spend lot of time finding how to remove and item from a UL. no luck.
please help me to remove ‘orange’ from below list. but not using the position / index of Orange. just by finding the string ‘orange’ by loop through.
Now we can just loop through each of the items, removing any that match.
var fruitToRemove = 'orange',
fruits = document.getElementById('fruits'),
items = fruits.getElementsByTagName('li'),
i;
for (i = items.length - 1; i >= 0; i -= 1) {
if (items[i].innerHTML === fruitToRemove) {
items[i].parentNode.removeChild(items[i]);
}
}
Why we go backwards through them is that removing an item from the list then doesn’t change the index numbers of the items that have not yet been processed, so multiple matching items can then be removed without causing problems.
A forward loop through the above would not remove the second orange, because once the first one is removed everything else below it moves up, so extra trickiness needs to occur to cater for that. To remove the need for such extra trickiness, the standard technique is to work through node lists in reverse, especially if any changes will be made to them.