Deleting rows in a table in HTML page containing data from XML

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cameokid
    New Member
    • Feb 2008
    • 10

    Deleting rows in a table in HTML page containing data from XML

    Hi,

    Here is the problem which i am facing. I am trying to delete rows (using nodes) containing XML data. I am doing this to add new set of data from XML file by using a dropdown selection.

    I am using the below code.(This is just a part of the code)

    Code:
    tab = document.getElementById('maintable').getElementsByTagName("tbody")[0];
    for(i=0;i<tab.childNodes.length;i++) {
    tab.removeChild(tab.childNodes[i]);
    }
    tab.childNodes refers to all the <tr> tags. Though i am referring to all the rows in the loop, i am able to delete only alternate rows in the table in IE and the other alternate rows get deleted in firefox.

    I need to delete all the rows. Can someone help me out with this?
  • pronerd
    Recognized Expert Contributor
    • Nov 2006
    • 392

    #2
    I think you may just need to reverse your loop.

    Since object oriented code works by just passing a reffernce to the object you are alwaysing working with just one instance of an object, no matter how many of them you make. I think your code is removing a row, which then causes all the rows in the array to be reordered.

    So if you for instance have a list or an array with four elements....

    [0], [1], [2], [3]

    and you remove its items one at a time. Your loop will remove the first item (index 0). Leaving you with .....

    [0], [1], [2]

    Then your loops moves up to index 1 which is now actually the second item in the array. Leaving you with ....

    [0], [2]



    So if you reverse your loop and remove them from the end you should get around this problem.

    Code:
        tab = document.getElementById('maintable').getElementsByTagName("tbody")[0];
        for(i=tab.childNodes.length; i>0; i++) {
            tab.removeChild(tab.childNodes[i]);
        }

    Comment

    • cameokid
      New Member
      • Feb 2008
      • 10

      #3
      Yeah that's great.

      It works fine when you delete in the reverse order.

      Thank you.

      Comment

      Working...