RemoveChild "Node Was Not Found" - Cant Work It Out
Solution 1:
There are a few issues here.
- Do not use duplicate IDs.
It is not valid, and will give unexpected results. Either use a class, or make the IDs unique.
- Do not do redundant DOM selection in a loop.
DOM selection is an expensive operation. It should be done once, outside the loop, then cached.
- There's no need to check for the
tagSelected
class inside the loop.
You used getElementsByClassName('tagSelected')
, so obviously they have that class.
It seems that you simply want to remove the elements with the given class.
// Fetch all elements in the document with the class 'tagSelected'
var selectTag = document.getElementsByClassName('tagSelected');
// Remove all of them.
while( selectTag[0] ) {
selectTag[0].parentNode.removeChild( selectTag[0] );
}
The reason that while( selectTag[0] ) {
works is that getElementsByClassName
returns a "live" NodeList. This means that when an element is removed from the DOM, the list is updated.
So because we're removing all the elements, all we need to do is run the loop as long as there's something at index [0]
.
Solution 2:
var p = document.getElementById('tableTr');
while(selectTag=document.getElementsByClassName('tagSelected')) {
if(!selectTag[0]) {
break;
}
if(selectTag[0].className=="tagSelected")
var c =selectTag[0];
p.removeChild(c);
}
}
First of all u have one error(might be) which is u dont have opening brace "{" after secound if condition.
You can rather do this actuly.
var p = document.getElementById('tableTr');
for(var i=0;i<document.getElementsByClassName('tagSelected')).length;i++)
{
var c = selectTag[i];
p.removeChild(c);
}
Post a Comment for "RemoveChild "Node Was Not Found" - Cant Work It Out"