/    Sign up×
Community /Pin to ProfileBookmark

delete html table row using javascript

I have added a bunch of items to an html table using javascript.

newCell0 = newRow.insertCell(cellCount);
newCell0.innerHTML = subInfo;

Now i want to go through the table and delete all the rows. I am trying this:

for(var i=1; i< count; i++)
{
tblBody.deleteRow(i);

}

However, it skips around! I even tried this:

tblBody.deleteRow(1);
tblBody.deleteRow(2);
tblBody.deleteRow(3);
tblBody.deleteRow(4);
tblBody.deleteRow(5);
tblBody.deleteRow(6);
tblBody.deleteRow(7);

After running that code, it deletes every other row! Which brings me to my next question? How the heck are rows numbered? I assumed it was 0,1,2,3,4,5,6,7 etc.

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@mrhooJul 01.2008 — the only child nodes a tbody can have are rows.

If tblBody refers to a tbody element:
[CODE]
while(tblBody.lastChild){
tblBody.removeChild(tblBody.lastChild);
}[/CODE]
Copy linkTweet thisAlerts:
@witzodeauthorJul 01.2008 — works perfect. Thank you!
Copy linkTweet thisAlerts:
@patrx-7Jul 01.2008 — The reason your previous attempts at deleting didn't work were because the rowIndex values of the table rows are automatically updated when a row is deleted or added.

Another way to delete all the rows would have been:
[CODE]while (tblBody.length > 0)
tblBody.deleteRow(0);[/CODE]

or if you don't want to calculate the length every time...
[CODE]var tblLength = tblBody.length;
for (i = 0; i < tblLength; i++)
tblBody.deleteRow(0);[/CODE]


Also, remember that javascript uses 0 index arrays, not 1 index arrays. All your previous tries would have skipped deleting the first row (tblBody.rows[0]). In the previous examples, you'll be continuously deleting the first row until all the rows have been deleted.

Hope this helps.


Edit by admin: no contact info, or advertising, permitted on the forum, thank you
Copy linkTweet thisAlerts:
@witzodeauthorJul 01.2008 — "the rowIndex values of the table rows are automatically updated when a row is deleted or added"

That is the most useful piece of information. I was also aware they are 0 index, I wanted to keep the first row. Thanks for the information! =]
×

Success!

Help @witzode spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...