Delete only the children divs from a parent div

Adrian Cross
Adrian Cross used Ask the Experts™
on
Hi, I'm trying to delete all the children divs that I created dynamically in a parent div. The parent div contains different controls, not just divs.

 var imgContainer = document.getElementById("ContentPlaceHolder1_div_Container");
    var childDivs = imgContainer.getElementsByTagName("div");

    var NumberOfDivs = childDivs.length;

    for (i = 0; i < NumberOfDivs; i++) {
        imgContainer.removeChild(childDivs[i]);
    }

Open in new window


If there is only one child div, the code works fine. However, when I append multiple divs I get the following error

"JavaScript runtime error: No such interface supported"

Any ideas?

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Multitechnician
Top Expert 2014
Commented:
when you remove the first one, the index of the second become the first one
so replace your"for" loop by this a while like this :
        while(imgContainer.getElementsByTagName("div").length > 0) {
            imgContainer.removeChild(childDivs[0]);
        }

Open in new window


        var imgContainer = document.getElementById("ContentPlaceHolder1_div_Container");
        while(imgContainer.getElementsByTagName("div").length) {
            imgContainer.removeChild(childDivs[0]);
        }

Open in new window

Author

Commented:
Excellent! Many thanks!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial