Вопрос

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.

Это было полезно?

Решение

If 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] );
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top