0

I want to append a new row in my table using Javascript but the new row should be like my previous rows.

I am using CSS to format my rows.

2
  • If you want to do this using javascript is there some particular reason why your question is tagged with java? Also it would be helpful if you showed your HTML structure as well as what you have tried so far to tackle the problem so that we can have some base for discussion. Commented Jun 11, 2011 at 17:20
  • When you decide on an answer, make sure you click the checkmark next to it to "accept" it. Commented Jun 12, 2011 at 17:05

4 Answers 4

4

If you are using jQuery it will be something like this:

$(document).ready(function() {
    $("table tr:last").clone().appendTo("table");
})

Replacing table with the id or class of your table (unless you only plan to have one table).

Sign up to request clarification or add additional context in comments.

Comments

2

Using good old Node.cloneNode(deep) along with HTMLTableElement.rows:

HTML:

<table id="foo">
    <tbody id="bar">
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
        </tr>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
        </tr>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
        </tr>
    </tbody>
</table>

JS:

var foo = document.getElementById("foo");
var bar = document.getElementById("bar");
var rows = foo.rows;
var lastRow = rows[rows.length-1];
var newRow = cloneRow(lastRow, true, bar);

function cloneRow(row, append, parent)
{
    var newRow = row.cloneNode(true); 
    if(append)
    {
        if(parent)
        {
            parent.appendChild(newRow);
        }
    }
    return newRow;
}

For comparison's sake, here's my code juxtaposed against the jQuery answer: http://jsperf.com/dom-methods-vs-jquery-with-tables

Comments

0

Let's say that your row has a css style of .row

So you could just use DOM methods to create a new tr, add the class="row" then add the appropriate amount of td

Comments

0

Here is a solution that avoids the use of the cloneNode method, and that do not copy the content, data or events of the previous last row, just its CSS attributes and class names.

The new row will have the same number of cell as the previous last row.

var lastRow = myTable.rows[myTable.rows.length-1];
var newRow = myTable.insertRow();
newRow.className = lastRow.className;
newRow.style.cssText = lastRow.style.cssText;
for (var i = 0; i < lastRow.cells.length; i++) {
    var newCell = newRow.insertCell(i);
    newCell.className = lastRow.cells[i].className;
    newCell.style.cssText = lastRow.cells[i].style.cssText;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.