...

View Full Version : Removing certain table rows



MissKay
02-28-2005, 11:47 AM
Morning all,

I'm trying to remove all but the first two rows of a table. Unfortunatly this script will be used on a numerous tables that I don't know the length of. I've got around this by assigning a variable the number of child nodes of the tbody ie the number of rows. What I can't seem to figure out though is how to get my code to step through the rows deleting them, starting at row 3. Any suggestions please?

Thanks

Kor
02-28-2005, 12:52 PM
give your table an id, say "tab":

var keep =2;//how many rows you wanna keep up on the table?
var oRows = document.getElementById('tab').getElementsByTagName('tr');
var root = oRows[0].parentNode;
for(var i=keep;i<oRows.length;i++){
root.removeChild(oRows[i])
}


if you wanna keep some special rows, the general approach could be

var keep = new Array(0,2,5);//keep the 1st, the 3rd, and the 6th
var oRows = document.getElementById('tab').getElementsByTagName('tr');
var root = oRows[0].parentNode;
for(var i=0;i<oRows.length;i++){
if(i!=keep[i]){
root.removeChild(oRows[i])
}
}

keep in mind that in javascript the index of elements in colections/arrays starts from 0.

MissKay
02-28-2005, 02:18 PM
Thanks Kor,

The first solution kind of worked. It wierdly removes every other row?!?! I think this may have something to do with the table though as every other row has a cell that spans both rows. It doesn't seem to repeat itself either as the next time I hit submit it takes out another row, but no more, etc.

Any suggestions.
Thanks again

liorean
02-28-2005, 02:38 PM
Oh, not that strange. You have a counter for which element to delete, and increment the counter each time you delete something. But if you take out table row number 3, row number 4 will automatically become number 3. So, when you next time remove a row, it'll be the row that now is number 4, which means that it's the row that was number 5 before.

Kor
02-28-2005, 04:23 PM
It doesn't seem to repeat itself...


After you have had deleted some rows, the order & and index of the remainded rows have changed, obviousely, as well.... So the next time when you perfome the function, other rows are to be deleted... can you detail a little bit your needs for us to be able to find a proper solution for?

MissKay
03-01-2005, 03:27 PM
Thanks for all the help guys. I went back and had a bit of a look at what I was trying to achieve and realised that if I sorted my tables out a bit life became much simpler.

The first two rows of my table always stay the same, and never get deleted. Everything below that can be altered/removed/added to etc. It seemed simpler to move the first two rows into the thead, and then just work with the rest in the tbody.

Thanks again for all of your help though.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum