Javascript removeChild function returns TypeError: value is not an object

I made a function in javascript that checks to see if the div element with the #stage id has any children, and if so, it should remove them when the function is called.

When I start the site, Firebug returns me an error that looks like this: TypeError: value is not an object.

This is my code: Declaring a variable step in javascript:

var stage = document.querySelector("#stage"); 

The part of the javascript function that gives the error:

 if (stage.hasChildNodes()) { for (var f1=0; f1<ROWS * COLUMNS; f1++) { stage.removeChild(stage.firstChild); } } 

HTML code:

 <body> <div id="stage"> </div> <script src="code.js"> </script> </body> 

I want to remove the child nodes with the id "stage"

Please help me solve this problem. If you need more information about my problem, please ask. Thanks.

+4
source share
2 answers

If you want to remove childNodes, the while loop is simpler

 var parentElement = document.getElementById('stage'); while (parentElement.hasChildNodes()) { parentElement.removeChild(parentElement.lastChild); } 
+2
source

I assume that you are getting an error message because you are just starting a for loop with a condition that does not match the number of child nodes. therefore, it is possible to get the first child in the parent element, which actually has no child element. As a result, parent.FirstChild will return null. Actually parent.removechild needs a DOM object, but your code supplies null. This may be a possible cause of your problem. Try it,

 while(stage.hasChildNodes()) { stage.removeChild( stage.childNodes[0] ); } 
+2
source

All Articles