Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a TH with TableRow.insertCell()?

I'm adding new rows to a table dynamically, with this code:

tbody = document.getElementById('tbody');
tr = tbody.insertRow(-1);
tr.id = 'last';
th = tr.insertCell(0);
td = tr.insertCell(1);

But what I actually got are two td cells. I want a th, as you can see.

It says the tagName property isn't changeable.

How can I do this?

Will I need to use 'normal' methods like createElement and appendChild?

like image 547
igorsantos07 Avatar asked Nov 24 '09 21:11

igorsantos07


People also ask

What is insertCell in Javascript?

insertCell() method inserts a new cell ( <td> ) into a table row ( <tr> ) and returns a reference to the cell. Note: insertCell() inserts the cell directly into the row. The cell does not need to be appended separately with Node. appendChild() as would be the case if Document.

How to add td to table in javascript?

The insertRow() method creates an empty <tr> element and adds it to a table. The insertRow() method inserts the new row(s) at the specified index in the table. Note: A <tr> element must contain one or more <th> or <td> elements. Tip: Use the deleteRow() method to remove a row.

How do you add another row in HTML?

Insert new row(s) at the beginning of a table. The insertRow() method inserts a new row at the specified index in a table, in this example, the first position (the beginning) of a table with id="myTable". Then we use the insertCell() method to add cells in the new row.


2 Answers

I don't see any official docs that allow you to do this.

W3C Documentation for TR / TR.insertCell

The createElement/appendChild will work though.

like image 72
scunliffe Avatar answered Oct 10 '22 12:10

scunliffe


I got it to work this way:

var table = d3.select("#table");
    table.html("");
    head = table.append("tr");
    head.append("th").text("column_header_1");
    head.append("th").text("column_header_2");

    chartData.forEach(function (obj) {
        row = table.append("tr");
        row.append("td").text(obj.datapoint_1);
        row.append("td").text(obj.datapoint_2);
like image 39
jason-hernandez-73 Avatar answered Oct 10 '22 11:10

jason-hernandez-73