HTML DOM, JavaScript to add/remove table rows (part 2)
I've promised you to improve table row delete function, that's what we will do today. So now we know the differences of DOM tree in different browsers. We saw that Firefox and Safari create additional text node "\n" so there are two ways to fix our delete row function: 1st - to delete these nodes, 2nd - just to pass them through.
1. Deleting "\n"
JAVASCRIPT:
-
function DelLastRow(tid) {
-
var myTbl=document.getElementById(tid);
-
var deltr=myTbl.lastChild;
-
while (deltr.nodeType==3)
-
{ myTbl.removeChild(deltr);
-
deltr=myTbl.lastChild; }
-
myTbl.removeChild(deltr);
-
}
2. Passing "\n" through
JAVASCRIPT:
-
function DelLastRow(tid) {
-
var myTbl=document.getElementById(tid);
-
var deltr=myTbl.lastChild;
-
while (deltr.nodeType==3)
-
{ deltr=deltr.previousSibling; }
-
myTbl.removeChild(deltr);
-
}
In last function we used previousSibling - this is the reference value to the previous neighbor node, you can also use nextSibling to go to the next neighbor node. Actually in DOM printing function we could make another cycle: 'while' instead of 'for':
JAVASCRIPT:
-
while (cur) {
-
...
-
cur=cur.nextSibling;
-
}
Very good site! I like it! Thanks!
Comment by Martin — August 30, 2008 @ 8:40 pm