2

I have a table which contains two rows.

<tr id="row1"><td>first row</td></tr>
<tr id="row2"><td>second row</td></tr>

I need to insert few rows between row1 and row2 using java script. I can achieve this by using java script create element. But I wish to add new rows using string html content. for example :

"<tr><td>This row is placed between first and second</td></tr>".insertAfter(first row Id);

is there way like this to add rows in between?

4
  • Yes I can use. But any reference code? Commented Apr 28, 2014 at 13:15
  • I always recommend not using jQuery, when you can. See below for a completely native JS solution. Commented Apr 28, 2014 at 13:17
  • 1
    @NickDugger Given that jQuery is JS, couldn't one argue that anything that can be done in jQuery can be done in native JS? Commented Apr 28, 2014 at 13:31
  • 1
    It doesn't make sense to use jQuery unless it is required.It adds a bloat of 19 kB and if you can do the same using plain js and are not using it specifically for doing something, you should not add it. Commented Apr 28, 2014 at 13:42

3 Answers 3

8
var newRow = document.createElement("tr");
newRow.innerHTML = "<td>This row is placed... etc.</td>";

var row2 = document.getElementById("row2");
row2.parentNode.insertBefore(newRow, row2);

Read up on it here: https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore

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

Comments

3

Use jQuery. There is a Function insertAfter();

$("#row1").insertAfter("your html");

http://jquery.com/

1 Comment

Suggesting to simply "use jQuery" is neither helpful nor productive. Always use native JS when you can.
0
var button = document.getElementById('insert');

var table = document.getElementById('table');

button.onclick = function() {

var position=Math.round(table.rows.length / 2);

var row = table.insertRow(position);

row.innerHTML = '<td>This row is placed between '+position+' and '+(parseInt(position)+1)+'</td>';
} 

 **after that if u can use like that u can increment ur row id also:**


 var rowId = '#' + tableId + ' tr';
    var k = 0;
    $(rowId).each(function () {
        var ObjInput = $(this).find('input[type=text],input[type=radio],input[type=checkbox],textarea,select,input[type=img],input[type=hidden],input[type=button],img');
        if (ObjInput != null) {
            for (var j = 0; j < ObjInput.length; j++) {
                var inputId = $(ObjInput[j]).attr('id');
                inputId = inputId.replace(/_[0-9]{1,2}/g, '_' + k);
                $(ObjInput[j]).attr('id', inputId);
                $(ObjInput[j]).attr('name', inputId);
            }
            k++;
        }
    });

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.