I have a JS function that takes a 2D array and a div. It creates a table from the array and appends it to the div. The div currently displays: [object HTMLTableElement]. How can I display it as the table instead?
I call the function with: createTable(myArray, $("#tblDiv"));
.
Later:
function createTable(array, tableDiv)
{
var tbl = document.createElement('table');
tbl.style.border = "1px solid black";
for(var i = 0; i < array.length; i++)
{
var tr = tbl.insertRow();
for(var j = 0; j < array[i].length; j++)
{
var td = tr.insertCell();
}
}
tableDiv.append("<br>" + tbl);
return;
}
I have a JS function that takes a 2D array and a div. It creates a table from the array and appends it to the div. The div currently displays: [object HTMLTableElement]. How can I display it as the table instead?
I call the function with: createTable(myArray, $("#tblDiv"));
.
Later:
function createTable(array, tableDiv)
{
var tbl = document.createElement('table');
tbl.style.border = "1px solid black";
for(var i = 0; i < array.length; i++)
{
var tr = tbl.insertRow();
for(var j = 0; j < array[i].length; j++)
{
var td = tr.insertCell();
}
}
tableDiv.append("<br>" + tbl);
return;
}
Share
Improve this question
asked Feb 2, 2014 at 19:48
AnasAnas
451 gold badge2 silver badges4 bronze badges
2
-
That's because you are concatenating an object with a string. >
document.createElement('table').toString() === [object HTMLTableElement]
– Ram Commented Feb 2, 2014 at 19:51 - I am trying execute AJAX query and from the response extract table and display that on a div. var doc = new DOMParser().parseFromString(resp, "text/html") var data = doc.getElementById("main_table_today"); document.getElementById("table_data").innerHTML = data.toString(); This shows [object HTMLTableElement] in 'table_data' . How do I fix this – user2677279 Commented Mar 20, 2020 at 0:46
1 Answer
Reset to default 7"<br>" + tbl
is going to evaluate to <br>[object HTMLTableElement]
. This is string concatenation, if you try to add a string to a non string it will be converted to a string then added so an HTMLTableElement
as a string is [object HTMLTableElement]
.
What you want to do is append the table by itself
tableDiv.append("<br>");
tableDiv.append(tbl);