I have such a question today.

I have a function that creates rows in a table using a loop. That is, the function receives the number of lines, and the function loops to create the lines. But these lines need to be added, just in turn already in the existing table, in the middle. Here is the function code.

function genTr(count) { for (var i = 0; i < count; i++) { var tr = document.createElement('tr'); tr.setAttribute('id', 'tr' + i + '_'); if (i == 0) { $('#tr' + i + '_').insertAfter("#oldtr"); } else { $('#tr' + i + '_').insertAfter('#tr' + (i-1) + '_'); } } 

id - #oldtr - a row in the table, after which it is necessary to insert rows into the trick.

There is nothing in the inspector, lines are not inserted! Maybe there is a solution? Thank you very much!

    2 answers 2

    The problem is that when the selector is received as a string, jQuery searches for elements that already exist on the page.

    Since the created element with id='tr' + i + '_' has not yet been added to the page. the selector $('#tr' + i + '_') will not find anything, and therefore will not add anything anywhere.

    To solve, it is enough to replace the line with the element created by itself:

     if (i == 0) { $(tr).insertAfter("#oldtr"); } else { $(tr).insertAfter('#tr' + (i-1) + '_'); } 
       const genTr = count => { let newTrs = [] let elAfter = document.getElementById('oldTr') for (let i = 0; i < count; i++) { let nt = document.createElement('tr'); nt.setAttribute('id', `id-${i}`) newTrs.push(nt) } newTrs.forEach((el) => { elAfter.after(el) elAfter = el }) }