Add row at any specific place inside the table

I’ve already got the code for this in the internet, but it only adds row at the end of the table, i want to be able to add at any index, is there any solution.
Here’s the code example

$(function () {

 $("#insertRow").on("click", function (event) {
        event.preventDefault();

        var newRow = $("<tr class='d-flex'>");
        var cols = '';

        // Table columns
cols += '<td><div class="form-group justify-content-center d-flex"><input type="number" class="form-control" id="slno"></div></td>';

  cols += '<td><div class="form-group"><button class="btn btn-dark text" id ="deleteRow">delete</button></div></td></tr>';

        // Insert the columns inside a row
        newRow.append(cols);

        
        // Insert the row inside a table
        $("table").append(newRow);
});

    // Remove row when delete btn is clicked
    $("table").on("click", "#deleteRow", function (event) {
        $(this).closest("tr").remove();
    });
});
1 Like

You could convert the table HTML object into an array. Then use array methods to insert at a certain index and then recreate the table from the array.

1 Like

Rather than use appendChild, consider using insertBefore: https://devdocs.io/dom/node/insertbefore

With that, you can add a row before a given sibling row.

1 Like

you can add a row before a given sibling row.

do you have an example (code) of that?

if you open the link there are some examples

2 Likes