最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript removeChild function returning TypeError: Value not an object - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 2

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] );
}
发布评论

评论列表(0)

  1. 暂无评论