Rohan
Rohan

Reputation: 1657

Delete elements with a particular class name (using javascript)?

I was trying to delete elements with a particular class name, but it doesnt work. Any idea why?

function delete_elems(){
    var my_elems = document.getElementsByClassName("my_elem");
        for(k=0; k<my_elems.length; k++){
            my_elems[k].parentElement.removeChild(my_elems[k]);
        }

}

I also tried:

function delete_elems(parentElem){
    var my_elems = document.getElementsByClassName("my_elem");
        for(k=0; k<my_elems.length; k++){
            parentElem.removeChild(my_elems[k]);
        }

}

Upvotes: 1

Views: 1791

Answers (2)

RobG
RobG

Reputation: 147413

The getElementsByClassName method returns a live node list, so iterating over it using an index and at the same time modifying the list (by removing nodes from the document) means that as elements are removed, the list is modified so what started as a list with 10 members will only have 9 once one is removed. If you remove item 0, then all items are re-indexed so what was item 1 is now 0, 2 is 1 and so on up to 8 (since there are only 9 left).

As noted by Dr. Molle, you may be able to avoid this issue by iterating over the list from the end.

You can avoid a counter altogether:

var el;
while ((el = my_elems[0])) {
  el.parentNode.removeChild(el);
}

Note that when using a NodeList, each time an element is removed, the list must be re-generated by the browser (regardless of which of the above methods is used) so this method will likely be slow where the nodeList is large.

You can avoid that by converting the list to an array first (simply iterate over it) in which case you can use either an incrementing or decrementing counter and not worry about missing members in the list (since it isn't modified when elements are removed from the document).

Upvotes: 4

Dr.Molle
Dr.Molle

Reputation: 117334

Begin at the end:

for(k=my_elems.length-1;k>=0; --k)

http://jsfiddle.net/doktormolle/fDNqq/

Upvotes: 4

Related Questions