Volodymyr Osypov blog

May 23, 2008

HTML DOM, JavaScript to add/remove table rows (part 2)

Filed under: JavaScript — Tags: , — admin @ 3:01 pm

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:
  1. function DelLastRow(tid) {
  2. var myTbl=document.getElementById(tid);
  3. var deltr=myTbl.lastChild;
  4. while (deltr.nodeType==3)
  5.    { myTbl.removeChild(deltr);
  6.      deltr=myTbl.lastChild; }
  7. myTbl.removeChild(deltr);
  8. }

2. Passing "\n" through

JAVASCRIPT:
  1. function DelLastRow(tid) {
  2. var myTbl=document.getElementById(tid);
  3. var deltr=myTbl.lastChild;
  4. while (deltr.nodeType==3)
  5.    { deltr=deltr.previousSibling; }
  6. myTbl.removeChild(deltr);
  7. }

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:
  1. while (cur) {
  2. ...
  3. cur=cur.nextSibling;
  4. }

1 Comment »

  1. Very good site! I like it! Thanks!

    Comment by Martin — August 30, 2008 @ 8:40 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress