I have a search form that uses AJAX to retrieve search results based on user submitted criteria. The results are displayed in a table dynamically created using JavaScript. The problem, however, was the results were being appended to the end of the existing table data. I needed a way to clear the table contents prior to adding the latest search results.
My first approach was to set the innerHTML property of the TBODY element from the results table to a zero-length string. For example:
var ctrl;
ctrl = document.getElementById('searchTBody');
ctrl.innerHTML = '';
This works fine in Firefox but it causes problems under IE. A different approach is needed. A couple of google searches turned up the removeChild method. Using it you can iterate through the childNodes collections to remove each child within the element. So I wrote the following JavaScript function:
function removeChildNodes(ctrl)
{
while (ctrl.childNodes[0])
{
ctrl.removeChild(ctrl.childNodes[0]);
}
}
To remove each child node from an element, get a reference to the element and pass it to the removeChildNodes function. For example:
var ctrl;
ctrl = document.getElementById('searchTBody');
removeChildNodes(ctrl);
This approach works for IE and Firefox. posted by Kirby | 05-Sep-2006 6:14 AM | comments (7)
Thanks Kirby, that trick helped make my afternoon.
posted by web-surfing programmer looking for answer | February 5 02:41 PMThanks so much - you saved me a lot of trouble, especially with the elegance of that while loop instead of a for loop, which was my first thought!
God bless!
Thanks for the tip Kirby. I found myself in the exact same scenario, working initially with Firefox and then moving to IE for cross-browser validation. I must say that it didn't surprise me when I found that IE didn't respond to my initial "innerHTML" approach and a couple of key words in a search engine led me straight to your solution!
Cheers!
Getting a wierd FFox error, good quick reference.
posted by 3686 | June 12 06:06 AMThanks kirby. i also encounter same problems with deleting the contents inside the TBODY.
Its already working now.
Was dealing with the same problem. After (finally) discovering that innerHTML wouldn't work I started looking for a removeChild solution and found your elegant solution.
Thanks
what if I want to remove just one set of tags?
example: li:em:a if i want re rmove or add the em tag?
Add Your Comment
