Delete all rows in an HTML table
Liberate your HTML table from its rows with this concise JavaScript snippet:
The creation above selects the first <table>
element on your page and performs a heartless while
loop to behead each row starting from top - until no survivors remain. It's your go-to solution for a quick table sweep.
Yearning for speed: The <tbody>
trick
Making a <tbody>
swap could turn your sad, lethargic table clearing into a blazing fast operation. Especially, when you're dealing with voluminous tables, this bring a pretty neat boost in performance:
No rows were harmed in the making of this clean-up; we just moved into a new <tbody>
. This keeps your table's beautiful structure in place, and is light-years faster than deleting rows one by one.
Saving your headers as Titanic
Your table might have some mighty column headers (<th>
) deserving preservation, while you dispose of the data rows. Protect your headers like they're Rose from the Titanic:
In this performance, the headers – usually nested in a comfy <thead>
– remain hale and hearty, while the <tbody>
is purged, all set for a new lease of data.
Taming the unruly: Dealing with Dynamic tables
Don't let the unceasingly dynamic nature of some tables deter you. In the world of wayward tables where new rows pop-in and vanish unannounced, roll-call (rowCount) can be a sanity-preserving ritual:
Take that, dynamic changes! Backward marching deletes ensure no rows sneak past.
Troubleshotting your way
Loaded table? Keep calm & DOM manipulate!
Attempting to vanquish rows from a monstrous table loaded with hundreds of rows? Your code's performance might whimper. Fear not! Keep your UI lively and kicking by:
- Giving your
<tbody>
a fresh makeover instead of chasing down every row. - Asynchronously waving the magic wand of
setTimeout
orrequestAnimationFrame
, to prevent any unseemly blockage of UI activities.
On a table hunt
Surely, some pages sprawl with a plague of tables. Never lose sight of your target: Tag them with id
:
Select your weapon wisely
Adapt to the environment: sometimes a shotgun is best, other times a scalpel.
- For minor, isolated tables, a
innerHTML
clean out is your Swift Swift. - Larger, dynamic tables? Stick with
deleteRow()
in a loop or just swap out thetbody
for structural consistency.
Was this article helpful?