1

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]);
        }

}
1
  • 1
    Please note that the W3C compliant parentNode property should be used, not the MS proprietary parentElement property. Commented Jan 25, 2012 at 3:28

2 Answers 2

4

Begin at the end:

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

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

Sign up to request clarification or add additional context in comments.

Comments

4

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).

2 Comments

So what's the best way to convert a NodeList to an array?
Just iterate over it and assign the nodes to an array: for (var a=[], i=0, iLen=nodeList.length; i<iLen; i++) a[i] = nodeList[i];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.