I made function in javascript that checks if the div element with an ID of #stage has any child nodes, and if so it has it to delete them when the function is called.
When I start the website, Firebug returns me an error, that goes like this: TypeError: Value not an object.
This is my code: Declaration of variable stage in javascript:
var stage = document.querySelector("#stage");
Part of javascript function that gives a 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 delete child nodes of with a ID of "stage"
Please help me to solve this problem. If you need more information about my problem please ask. Thanks.
I made function in javascript that checks if the div element with an ID of #stage has any child nodes, and if so it has it to delete them when the function is called.
When I start the website, Firebug returns me an error, that goes like this: TypeError: Value not an object.
This is my code: Declaration of variable stage in javascript:
var stage = document.querySelector("#stage");
Part of javascript function that gives a 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 delete child nodes of with a ID of "stage"
Please help me to solve this problem. If you need more information about my problem please ask. Thanks.
Share Improve this question edited Aug 18, 2016 at 7:48 ikellenberger 868 bronze badges asked Apr 18, 2013 at 19:59 depecheSouldepecheSoul 9641 gold badge12 silver badges31 bronze badges 1-
Is there a reference with
Value
somewhere before that code? – epascarello Commented Apr 18, 2013 at 20:06
2 Answers
Reset to default 2If you want to remove the childNodes, a while loop is easier
var parentElement = document.getElementById('stage');
while (parentElement.hasChildNodes()) {
parentElement.removeChild(parentElement.lastChild);
}
I guess that, you are getting an error because, you are just running your for loop with a condition which does not matches the child nodes count. so, There is possibility to get the first child the in the parent element which really does not has any child. As a consequence, the parent.FirstChild will returns null. Actually parent.removechild needs a DOM object but your code will supplies null to that.This might be a possible reason for your issue. Try this,
while(stage.hasChildNodes()) {
stage.removeChild( stage.childNodes[0] );
}