H.Tirit
H.Tirit

Reputation: 15

Insert cells in specific column in Table

I have a Table with 3 thead.

I'm trying to insert cells in the second column.

I put the insertCell function as follows:

cell = row.insertCell(2); 

but it doesn't work.

This is my code :

function add() {
    j++;
    count++;
    var table = document.getElementById('table0');
    var row = table.insertRow(-1);
    cell = row.insertCell(1);
    text = count;
    cell.appendChild(document.createTextNode(text));


}

Here is my JSFiddle code

Can anyone help me?

Upvotes: 0

Views: 3543

Answers (2)

gilly3
gilly3

Reputation: 91497

The index you pass to row.insertCell(index) must be less than or equal to row.cells.length. In your case, since row is a brand new row, row.cells.length is 0, so you must pass 0 or -1.

Consider the HTML for your table. How would you write the HTML for a row containing a single cell, in the 2nd column? You can't do it! If there is a cell in the second column, there must also be a cell in the first column.

To create a new row in table, with a cell in the second column:

var row = table.insertRow(-1);
var firstCell = row.insertCell(-1);
var secondCell = row.insertCell(-1);

To give it the appearance of having no cell in the first column, use CSS to git rid of the border and any other styles that make it look like a cell:

firstCell.className = "empty";
.empty {
    border: 0 none;
}

http://jsfiddle.net/54pmo8oy/14/

Upvotes: 2

dgavian
dgavian

Reputation: 250

I'm not clear whether this is what you're trying to do, but hopefully it's close. Clicking the button will add a new cell to the second column with each click:

(function () {
    var count = 1,
        add = function () {
            var table = document.getElementById('table0'),
                row = table.rows[0],
                cell = row.insertCell(1),
                text = count;
            cell.innerHTML = text;
            count++;
        };
    document.getElementsByTagName('button')[0].addEventListener('click', function () {
        add();
    });
    add();
}());

JSFiddle

Upvotes: 0

Related Questions