Reputation: 145
I have made a chat application in node js, in which I dynamically load the messages of each user. When the name of the user is clicked, their messages are retrieved in the mean time. But what I want to do is, when I retrieve the messages of a user and try to retrieve messages of a second or third user, I want to remove the messages which are already retrieved. Which are the children of a parent div element, which has the class name ("indChatBody")
and the each message are the children of this class, and I just make these children dynamically through javascript, and that is why I want to remove these children with javascript.
The code I tried is :
var chatBody = document.getElementsByClassName("indChatBody")[0]
var ch = document.getElementsByClassName("mess");
var len = chatBody.children.length;
for(var i =0;i<len;i++){
console.log(i);
chatBody.removeChild(ch[i]);
}
This code display a runtime error, which is
custom.js:108 Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'.
The code I have written so far, do remove some of the children but then display the error, by executing it in the console of the chrome, again and again it remove the whole children then. But I don't know why I am getting the exception.
Upvotes: 0
Views: 90
Reputation: 1379
ch is not an array but a list, that mean that when you remove one element, it is removed from the list too. So you change the length of your list by removing. you don't need the length
while(ch[0]){
chatBody.removeChild(ch[0]);
}
Upvotes: 1
Reputation: 4020
You are looping from 0 to the original length of your array. But each time you loop, you're removing an element from this array. At some point, you are out of index.
Instead of using an array and have potential issues with its length, you can combine a while loop, element.hasChildNodes() and remove the first child until there is no more child :
var chatBody = document.getElementsByClassName("indChatBody")[0]
while (chatBody.hasChildNodes()) {
chatBody.removeChild(chatBody.firstChild);
}
<div class="indChatBody">
<div class="mess">
Message #1
</div>
<div class="mess">
Message #2
</div>
<div class="mess">
Message #3
</div>
</div>
Upvotes: 1