Dynamically Creating and Removing Elements in javascript
I was thinking im comfortable with adding and removing elements in js till two days ago when i ran into this trouble.
Ok , pls this is my problem:
I was trying to dynamically create divs, append to an elemnt on the page, add a handle to the new div i created in an array, then run a loop later and remove all the divs in the array (both from the array and the page)
This is my code fo开发者_开发技巧r creating the divs:
var this_object=this;this.tempdivs=new Array();var thandle='';
var t=document.createElement('div');var br=document.createElement('br');
var txt=document.createTextNode(content_body);
t.appendChild(content);t.appendChild(txt);t.appendChild(br);
thandle=this_object.chat_rec_handle.appendChild(t);
this_object.tempdivs.push(thandle);
this_object.chat_rec_handle is where i append after creation, it actually gets appended.
My problem is when is want to remove the divs that i have created
var divlength=this_object.tempdivs.length;
for(var i = 0; i < divlength; i++)
{
var tempobj=this_object.tempdivs[this_object.tempdivs.length-1];
alert(tempobj.parentNode);
/* this alert gives me null, does that mean the parent no longer exists? */
tempobj.parentNode.removeChild(tempobj);
this_object.tempdivs.pop();
}
This is very frustrating, but i know codes are not wrong, please what am i doing wrong?
First of all, why not just use i
as the index into the array of divs? The first line after the beginning of your for loop should be:
var tempobj=this_object.tempdivs[i];
And then you can delete this line:
this_object.tempdivs.pop();
Second, you may want to check to make sure the element has a parent (i.e. not already removed) before trying to remove it:
tempobj.parentNode && tempobj.parentNode.removeChild(tempobj);
That change will prevent the error from occurring, but it will not fix its cause. You'll have to find out why. Without any other code posted, I cannot say anything else.
精彩评论