简体   繁体   中英

How can I remove a list of divs from a parent div?

I have a problem with JavaScript.

I need to delete a list of divs from the parent div. So i tried this:

var divs = parent.getElementsByTagName("div");
if(divs != null)
{
    for(var v = 0; v < divs.length; v++)
    {
        parent.removeChild(divs[v]);
    }
}

But the problem is, that JS doesn't remove all of the divs. JS only removes the half of the list.

I also tried this:

var divs = parent.getElementsByTagName("div");
if(divs != null)
{
    for(var v = 0; v < divs.length; v++)
    {
        parent.removeChild(divs[0]);
    }
}

But with the same results

Please help?

var divs = parent.getElementsByTagName("div");
while(divs[0]) {
    divs[0].parentNode.removeChild(divs[0])
}

The list returned by getElementsByTagName is live . This means it gets updated as you remove the DOM objects, so you length isn't the same on each cycle.

Here's a fiddle .

Why don't you try something like:

var divs = parent.getElementsByTagName("div");
if (divs.length > 0) {  // Technically unnecessary, as the for loop just won't run if there aren't any elements returned
    for (var v = divs.length; v >= 0; v--) {
        divs[v].parentNode.removeChild(divs[v]);
    }
}

As an explanation of why this is correct, the use of removeChild must be used to remove an actual child of the parent node. If div[v] is a descendent (you know, like nested inside of another element - not a div - that is an actual child of parent ). This is the safe way to remove an element when you have a reference to it. You guarantee the parent node of the element is removing it, and therefore is valid. If you check your console for trying to use parent.removeChild like yours and others code, there is an exception thrown for any descendent - http://jsfiddle.net/ujaSv/

Although it's important to point out that a better alternative to a for loop for this is:

while (divs[0]) {
    divs[0].parentNode.removeChild(divs[0]);
}

I did not think of this brilliance - this was decided in another answer/comment area.

Two solutions:

1: count down

var divs = parent.getElementsByTagName("div");
if(divs != null)
{
    for(var v = divs.length - 1; v >= 0; v--)
    {
        parent.removeChild(divs[0]);
    }
}​

2: cache length:

var divs = parent.getElementsByTagName("div");
if(divs != null)
{
    for(var v = 0, len = divs.length; v < len; v++)
    {
        parent.removeChild(divs[0]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM