Jquery iterating over newly created elements

I am trying to add new rows to my table and save them to the DB.

First, I use .append () to add rows to the table:

$("#tablename").append("<tr id='newRow'><td>newly added row</td></tr>");

The add function works great. My page displays the correct result.

However, I cannot select them using

$("#newRow").each(function () { alert "it never reaches here!"; });

I assume this is because elements are added after loading the DOM. Can someone please tell me how can I repeat all my recently added items?

Thank.

+3
source share
3 answers

class , unqiue ( HTML ), :

$("#tablename").append("<tr class='newRow'><td>newly added row</td></tr>");

$(".newRow").each(function () { alert "it never reaches here!"; });
+10

Nick , :

$(function(){
  //add a class to mark the last row on load
  $('#tableName tr:last').addClass('lastRow');

  // ...

  // select new rows when you click save
  $('input:submit').click(function(){
     $('#tableName tr.lastRow').nextAll().each(function(){
        alert('added row');
     });
  });
});
+1

If you just need to loop the new lines, you can do this:

var rows = $("<tr class='newRow'><td>newly added row</td></tr>").appendTo('#tablename');
rows.each(function () { alert "it never reaches here!"; });
-1
source

Source: https://habr.com/ru/post/1746102/


All Articles