Removing an item from <UL> by string

Hai folks,

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.

<ul>
<li>mango</li>
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>

Do you want to remove the word, the whole list item, or replace orange with some other text?

Let’s put an identifier on that UL element, so we can gain easy access to it from a script.


<ul id="fruits">
    <li>mango</li>
    <li>apple</li>
    <li>orange</li>
    <li>banana</li>
</ul>

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.


<ul id="fruits">
    <li>mango</li>
    <li>apple</li>
    <li>orange</li>
    <li>orange</li>
    <li>banana</li>
</ul>

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.

Hai rguy, thanks for ur intrest in my question. any way its answerd now :slight_smile:

Hai paul,
works charm! what a relief !!!
thanks for the step by step guide.really appreciated.