Search code examples
javascripthtmlhtml-tablerow

Insert row after row Javascript


I'm not so good at Javascript and can't get one thing working. I have a table, something like this:

<table>
    <tr><td>test #1</td><td><a href="#">Here we go1!</a></td></tr>
    <tr><td>test #2</td><td><a href="#">Here we go2!</a></td></tr>
    <tr><td>test #3</td><td><a href="#">Here we go3!</a></td></tr>
</table>

And I need to insert new row with some content (not clone) after row with pressed link.

So in other words, after pressing on <a> in first row, the table have to be like this:

<table>
    <tr><td>test #1</td><td><a href="#">Here we go1!</a></td></tr>
    <tr><td>some content here</td><td><a href="#">some content here</a></td></tr>
    <tr><td>test #2</td><td><a href="#">Here we go2!</a></td></tr>
    <tr><td>test #3</td><td><a href="#">Here we go3!</a></td></tr>
</table>

I really tried to do something but it was always inserting before of after table.

UPDATE:

My JS code to insert new row looks something like this: (I tried to use one solution posted here but it doesn't work).

function RowAdd()
{
    var table=document.getElementById("test");
    var last=$(this).closest("tr").prevAll().length;
    var row=table.insertRow(last);
    row.insertCell(0);
    row.cells[0].innerHTML="test";
    row.insertCell(1);
    row.cells[1].innerHTML="test";
    row.insertCell(2);
    row.cells[2].innerHTML="test";
}


Solution

  • If I understand you need to do that, right ?

    http://jsfiddle.net/OxyDesign/v7swo505/

    JS (with jQuery)

    $(document).ready(function(){
        $('body').on('click','table a', function(e){
            $(this).closest('tr').after('<tr><td>New Content 1</td><td><a href="#">New Content 2</a></td></tr>');
        });
    });