Here is the code below I am using the remove cells (which have been selected) from a table. It works some of the time, but then other times it brings up a “Node was not found” code:
“8” (NS_ERROR_DOM_NOT_FOUND_ERR)
Can’t seem to figure how to do it. Any help would be great.
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);
}
}
I have a PHP script that populates the table and thats about it to my HTML:
<div id="uploadTag">
<table class="tagBlock" id="tableTag" cellspacing="5px;">
<?php
$uploadlist=substr($uploadlists, 0, -1);
$uploadList=explode(";",$uploadlist);
$i=0;
foreach($uploadList as $key=>$list){
if($i==0)
{ ?>
<tr id="tableTr">
<?php }
$i++; $up="up".($key+1);
$imageext = substr(strrchr($list, '.'), 1);
$val=$list;
if ($imageext=='png' || $imageext=='bmp' || $imageext=='gif' || $imageext=='tif' || $imageext=='jpg')
{
$val="<image>";
}
?><td id="<?php echo $up; ?>" class="tagBlock" title="<?php echo $list; ?>"><div id="<?php echo $up; ?>" class="tagBlockW" title="<?php echo $list; ?>"><?php echo "$val"; ?></div></td> <?php
if($i==7){ $i=0;?> </tr> <?php }?>
<?php }
?>
</tr>
</table>
</div>
There are a few issues here.
It is not valid, and will give unexpected results. Either use a class, or make the IDs unique.
DOM selection is an expensive operation. It should be done once, outside the loop, then cached.
tagSelectedclass 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.
The reason that
while( selectTag[0] ) {works is thatgetElementsByClassNamereturns 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].