By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,053 Members | 1,595 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,053 IT Pros & Developers. It's quick & easy.

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

P: 10

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)

Expand|Select|Wrap|Line Numbers
  1. tab = document.getElementById('maintable').getElementsByTagName("tbody")[0];
  2. for(i=0;i<tab.childNodes.length;i++) {
  3. tab.removeChild(tab.childNodes[i]);
  4. }
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?
Apr 1 '08 #1
Share this Question
Share on Google+
2 Replies

Expert 100+
P: 392
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.

Expand|Select|Wrap|Line Numbers
  1.     tab = document.getElementById('maintable').getElementsByTagName("tbody")[0];
  2.     for(i=tab.childNodes.length; i>0; i++) {
  3.         tab.removeChild(tab.childNodes[i]);
  4.     }
Apr 1 '08 #2

P: 10
Yeah that's great.

It works fine when you delete in the reverse order.

Thank you.
Apr 2 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.