Reputation: 191
I'm creating thead
of table dynamically. Problem is, when I call my method for the first time it creates headers perfectly but when I call it again on the same table, it doesn't remove the previous headers. How can I clear previous thead
?
HTML
<table id="tblActivitySummary" class="display nowrap" cellspacing="0" width="100%">
<span class="table-mainhead">Activity Summary</span>
</table>
JQuery
function CreateHTMLTable(tableId, displayColumnNames) {
var columnNames = [];
for (var k in displayColumnNames[0]) {
columnNames.push(k);
}
var $toAttach = $("<thead><tr></tr></thead>");
for (var i = 0; i < columnNames.length; i++) {
var $thead = $("<th></th>");
$thead.text(columnNames[i]); //columnNames is array of string containing column names
$toAttach.find("tr").append($thead);
}
$(tableId).append($toAttach);
}
I tried to empty like this before calling CreateHTMLTable
but doesn't work:
$('#tblActivitySummary').empty();
CreateHTMLTable('#tblActivitySummary', displayColumnNames);
Upvotes: 1
Views: 1102
Reputation: 23859
It is adding more thead
s because you've used .append
, which appends the contents in the specified container.
$(tableId).append($toAttach);
Instead of appending, you can directly use .replaceWith()
to replace the tag with the new one.
$(tableId + " thead").replaceWith($toAttach);
Edit:
The following snippet adds the ability to add the thead
first time when it doesn't exist:
$(tableId + " thead").length === 0 ? $(tableId).append($toAttach) : $(tableId + " thead").replaceWith($toAttach);
Upvotes: 2