I'm trying to create a table in JavaScript and then use it on a page, but this is difficult to do
The goal is for the table to represent a set of hospital beds that will be managed through the HTML page.
How to do this?
I'm trying to create a table in JavaScript and then use it on a page, but this is difficult to do
The goal is for the table to represent a set of hospital beds that will be managed through the HTML page.
How to do this?
To create dynamic elements with JavaScript, you must use document.createElement
. and to add to another existing html element, you must use Node.appendChild()
. .
To create a table, you should call something like:
var novaTabela = document.createElement("table");
To add it to an existing DIV as:
<div id="test"></div>
You do this:
var novaTabela = document.createElement("table");
document.getElementById("test").appendChild(novaTabela);
The table usually needs (is recommended) <thead>
and <tbody>
(sometimes you can use <tfoot>
, but it's optional).
To create <thead>
and <tbody>
do this:
var tabela = document.createElement("table");
var cabecalho = document.createElement("thead");
var corpo = document.createElement("tbody");
tabela.appendChild(cabecalho);
tabela.appendChild(corpo);
document.getElementById("test").appendChild(tabela);
Note: Within
<thead>
, use<th>
instead of<td>
Read about tags:
innerHTML
Some will criticize, but will not kill anyone using innerHTML
. sometimes you can try something like:
var container = document.getElementById("container");
container.innerHTML = [
'<table>',
'<thead>',
'<tr>',
'<th>id</th>',
'<th>col1</th>',
'<th>col2</th>',
'<th>col3</th>',
'</tr>',
'</thead>',
'<tbody>',
'<tr>',
'<td>1</td>',
'<td>data</td>',
'<td>data</td>',
'<td>data</td>',
'</tr>',
'<tr>',
'<td>2</td>',
'<td>data</td>',
'<td>data</td>',
'<td>data</td>',
'</tr>',
'<tr>',
'<td>3</td>',
'<td>data</td>',
'<td>data</td>',
'<td>data</td>',
'</tr>',
'</tbody>',
'</table>'
].join("\n");
table {
border: 1px #c0c0c0 solid;
width: 100%;
}
table th {
background-color: #00f;
color: #fff;
}
table td {
background-color: #f0f0f0;
color: #0c0c0c;
}
<div id="container"></div>
I created this function for you, if you want to use it.
function criarTabela(conteudo) {
var tabela = document.createElement("table");
var thead = document.createElement("thead");
var tbody=document.createElement("tbody");
var thd=function(i){return (i==0)?"th":"td";};
for (var i=0;i<conteudo.length;i++) {
var tr = document.createElement("tr");
for(var o=0;o<conteudo[i].length;o++){
var t = document.createElement(thd(i));
var texto=document.createTextNode(conteudo[i][o]);
t.appendChild(texto);
tr.appendChild(t);
}
(i==0)?thead.appendChild(tr):tbody.appendChild(tr);
}
tabela.appendChild(thead);
tabela.appendChild(tbody);
return tabela;
}
document.getElementById("tabela").appendChild(criarTabela([
["id", "nome", "idade"],
[1, "matheus", 16],
[2, "cristian", 16],
[3, "pedro", 10],
[4, "henrique", 10]
]));
<div id="tabela"></div>