I am using Javascript to dynamically create a table, and want to make a header-style cell at the beginning of each row. So my question is how I can do this, seeing as insertCell
creates only a normal <td>
element and not a <th>
.
Some things I've tried (via the Tryit editor at w3schools; I have no reason to suspect that any other usage will behave differently) and didn't work:
I've seen a suggestion to create the
<th>
element independently and then add it to the<tr>
element as a child. When I do this, however, it is not added as a table cell, i.e. it is not affected by the table border, does not count toward the array of cells (i.e. if you doinsertCell(1)
, it inserts after the first cell not counting the<th>
), and does not get the special bold/center format for a<th>
cell.I've attempted to use
insertCell
to make a dummy cell and thenreplaceChild
with an independently created cell; this had the same result as above.I've tried to make a
<td>
cell via insertCell and simply bold and center it manually, butmyCell.style.fontWeight="bold"
andmyCell.align="center"
don't seem to work (they just end the function, as bad mands do in JavaScript), and likewise trying to use CSS doesn't work. So maybe I just have bad syntax or something, but I've got no clue what to do. Any help would be appreciated.
Attempt 1:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to insert new cell(s) at the end of the table row.</p>
<table border="1">
<th>1</th>
<td>2</td>
</tr>
<tr id="myRow">
</tr>
<tr>
</table><br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var newRow = document.getElementById("myRow");
var header=document.createElement("th").appendChild(document.createTextNode("a"));
newRow.appendChild(header);
var enablesLoc=newRow.insertCell(0).appendChild(document.createTextNode("b"));
}
</script>
</body>
</html>
Result: "1" is bolded with a border, "2" and "b" are unbolded with a border (as they should be), "a" is unbolded with no border.
Attempt 2:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to insert new cell(s) at the end of the table row.</p>
<table border="1">
<th>1</th>
<td>2</td>
</tr>
<tr id="myRow">
</tr>
<tr>
</table><br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var newRow = document.getElementById("myRow");
var header=newRow.insertCell(0).appendChild(document.createTextNode("a"));
header.style.fontWeight="bold";
var enablesLoc=newRow.insertCell(1).appendChild(document.createTextNode("b"));
}
</script>
</body>
</html>
Result: The button adds cell "a" unbolded but not cell "b".
I am using Javascript to dynamically create a table, and want to make a header-style cell at the beginning of each row. So my question is how I can do this, seeing as insertCell
creates only a normal <td>
element and not a <th>
.
Some things I've tried (via the Tryit editor at w3schools; I have no reason to suspect that any other usage will behave differently) and didn't work:
I've seen a suggestion to create the
<th>
element independently and then add it to the<tr>
element as a child. When I do this, however, it is not added as a table cell, i.e. it is not affected by the table border, does not count toward the array of cells (i.e. if you doinsertCell(1)
, it inserts after the first cell not counting the<th>
), and does not get the special bold/center format for a<th>
cell.I've attempted to use
insertCell
to make a dummy cell and thenreplaceChild
with an independently created cell; this had the same result as above.I've tried to make a
<td>
cell via insertCell and simply bold and center it manually, butmyCell.style.fontWeight="bold"
andmyCell.align="center"
don't seem to work (they just end the function, as bad mands do in JavaScript), and likewise trying to use CSS doesn't work. So maybe I just have bad syntax or something, but I've got no clue what to do. Any help would be appreciated.
Attempt 1:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to insert new cell(s) at the end of the table row.</p>
<table border="1">
<th>1</th>
<td>2</td>
</tr>
<tr id="myRow">
</tr>
<tr>
</table><br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var newRow = document.getElementById("myRow");
var header=document.createElement("th").appendChild(document.createTextNode("a"));
newRow.appendChild(header);
var enablesLoc=newRow.insertCell(0).appendChild(document.createTextNode("b"));
}
</script>
</body>
</html>
Result: "1" is bolded with a border, "2" and "b" are unbolded with a border (as they should be), "a" is unbolded with no border.
Attempt 2:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to insert new cell(s) at the end of the table row.</p>
<table border="1">
<th>1</th>
<td>2</td>
</tr>
<tr id="myRow">
</tr>
<tr>
</table><br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var newRow = document.getElementById("myRow");
var header=newRow.insertCell(0).appendChild(document.createTextNode("a"));
header.style.fontWeight="bold";
var enablesLoc=newRow.insertCell(1).appendChild(document.createTextNode("b"));
}
</script>
</body>
</html>
Result: The button adds cell "a" unbolded but not cell "b".
Share Improve this question edited Aug 13, 2018 at 16:10 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jan 1, 2014 at 2:52 user1837296user1837296 5961 gold badge4 silver badges13 bronze badges 15-
5
document.createElement("th")
, for all your element-creating needs. – Ry- ♦ Commented Jan 1, 2014 at 2:53 -
1
@user1837296
parentElement.appendChild(returnValueOf_createElement)
– Benjamin Gruenbaum Commented Jan 1, 2014 at 2:55 -
3
appendChild
(notaddChild
) on the row, not the entire table. Also, “they just end the function, as bad mands do in JavaScript” is not correct and you should check your console. Also also, if you’re using W3Schools as a resource, be warned that it’s not a very good one. – Ry- ♦ Commented Jan 1, 2014 at 2:55 - 1 Please show your existing JavaScript. It's easier for us to help by adding to or fixing your existing code rather than doing the whole thing from scratch. – nnnnnn Commented Jan 1, 2014 at 2:58
- 2 "W3Schools has problems, but I don't remember hearing that that extended to their tester" - W3Schools seems to be trying to make money dishonestly: they pretend to be associated with the W3C when they are not, so people who are fooled by this use their resources and contribute to their ad revenue. Plus they sell worthless "certifications" - I don't know how that could be described as anything but a scam. Therefore even in the cases where they have useful tools any use of their site at all is going to contribute to their profits by helping them to get advertisers, etc. – nnnnnn Commented Jan 1, 2014 at 3:11
4 Answers
Reset to default 4The following code shows everything that should get you going:
function addTable(){
var table = document.createElement("table");
var tr = document.createElement("tr");
var th = document.createElement("th");
var td = document.createElement("td");
td.innerText = "im a td";
th.innerText = "im a th";
tr.appendChild(th);
tr.appendChild(td);
table.appendChild(tr);
var out = document.getElementById("out");
out.appendChild(table);
}
You have to call the function and an div with id out <div id=out>...</div>
must be in the document. Disclaimer: i only tested this code in chrome
Update to address your points
You wrote I've seen a suggestion to create the <th> element independently and then add it to the <tr> element as a child. When I do this
it is not added as a table cell
what do you mean by that and what mand are you using,is not affected by the table border
the reason could be because it contains not text,does not count toward the array of cells (i.e. if you do insertCell(1)
i do not understand this either. According to the specs on insertCell it insert an emptytd
and returns a reference. So insertCell has no array, If you tryvar table = document.getElementById("myTable")
and thentable.rows[0].cells.length
it returns the number of cells including theth
-cell.it inserts after the first cell not counting the th
according on my tests at least in chrome this is not the case; it depends on how you call the method:table.rows[1].insertCell(-1);
adds a cell at the second row (zero based array) at the end andtable.rows[2].insertCell(1);
adds in the third row a cell on position 2 (again zero based) if you usetable.rows[3].insertCell(0);
the cell is inserted into the 4th. row at the beginning,and does not get the special bold/center format for a th cell
this was not the case for me as well
Disclaimer: i only tested this code in chrome
The html
<button onclick="addRow()">add rows</button><br />
<button onclick="addColumn()">add column</button>
<table border="1" id="myTable">
<tr>
<th>1</th>
<td>2</td>
</tr>
</table>
And the javascript
function addRow()
{
var table = document.getElementById("myTable");
var tr = document.createElement("tr");
var th = document.createElement("th");
var td = document.createElement("td");
td.innerText = "im a td";
th.innerText = "im a th";
tr.appendChild(th);
tr.appendChild(td);
table.appendChild(tr);
}
function addColumn(){
var table = document.getElementById("myTable");
var rows = table.rows;
console.log("rows", rows);
for (var i = 0; i < rows.length; ++i) {
// td = rows[i].cells;
var td = document.createElement("td");
td.innerText = i;
rows[i].appendChild(td);
}
}
Based on DOM Level 2 HTML you can not use insertCell
since it Insert[s] an empty TD cell into this row
. But you want to add a th
According to DOM Level 3 Core you can use appendChild
since it adds the node newChild to the end of the list of children of this node. If the newChild is already in the tree, it is first removed.
So therefore you have to create the elements in the right order: create the row, add the first cell as th
then add other cells as td
by using append child.
You may take a look at a demo of the above code
The .appendChild()
method returns the element being appended. Which means on this line:
var header=document.createElement("th").appendChild(document.createTextNode("a"));
...your header
variable is actually the text node, not the th element - so then newRow.appendChild(header);
appends just the text node to the row, not the new th.
Try something like this instead:
var newRow = document.getElementById("myRow");
var header = document.createElement("th");
header.appendChild(document.createTextNode("a"));
newRow.appendChild(header);
Demo: http://jsfiddle/PtzRL/
Note that if you actually want to append new rows then your newRow
variable should not be getting a reference to an existing row in the table, you should give an id to the table:
<table id="myTable">
...and then create a new row and add that to the table:
var table = document.getElementById("myTable");
var newRow = document.createElement("tr");
table.appendChild(newRow);
Demo: http://jsfiddle/PtzRL/1/
(Note also that the starting html you show has an error: you're missing the first <tr>
just after the <table>
tag, and you have an extra <tr>
just before the closing </table>
tag.)
Is this what you were trying to do?
function myFunction = function() {
var newRow, newHeader, newCell;
newRow = document.getElementById("myRow");
newHeader = document.createElement("th");
newHeader.innerText = "a";
newRow.appendChild(newHeader);
newCell = document.createElement("td");
newCell.innerText = "b";
newRow.appendChild(newCell);
}
If you want the button to add new rows rather than filling in a blank row you put there already, try something like this: HTML:
<body>
<table id="myTable" border="1">
<tr>
<th>1</th>
<td>2</td>
</tr>
</table>
<button onclick="myFunction()">Try it</button>
</body>
JavaScript:
function myFunction = function() {
var myTable, newRow, newHeader, newCell;
myTable = document.getElementById("myTable");
newRow = document.createElement("tr");
newHeader = document.createElement("th");
newHeader.innerText = "a";
newRow.appendChild(newHeader);
newCell = document.createElement("td");
newCell.innerText = "b";
newRow.appendChild(newCell);
myTable.appendChild(newRow);
}
The function need to altered like this I believe...
function myFunction()
{
var newRow = document.getElementById("myRow");
var header=document.createElement("th");
header.appendChild(document.createTextNode("a"));
newRow.appendChild(header);
var enablesLoc=newRow.insertCell(0);
enables.appendChild(document.createTextNode("b"));
}