JQuery: add row to table and select it in DOM

I want to add a row to a table and then use it as a DOM object. Assume the following HTML:

<table> <tr class="existing-row"><td> <a>add new row</a> </td></tr> <tr class="existing-row"><td> <a>add new row</a> </td></tr> </table> 

I am using the following JavaScript with jQuery to insert a string:

  function addNewRow(addNewRowLink) { var currentRow = addNewRowLink.closest('tr'); currentRow.after('<tr class="added-row"><td>This is new</td></tr>'); var newRowInDomTree = currentRow.next('tr'); //This does not work } 

The variable newRowInDomTree contains tr.existing-row instead of a tr.added-row . It seems that the DOM tree is not updating, but I do not understand why.

Any ideas?

Thanks for the advanced.

+4
source share
4 answers

Your code should work, except that I don’t see how it is called, so I don’t know what addNewRowLink actually addNewRowLink .

An alternative would be to keep a link to the new element when it is created. Like this:

 function addNewRow(addNewRowLink) { var currentRow = addNewRowLink.closest('tr'); var newRowInDomTree = $('<tr class="added-row"><td>This is new</td></tr>') .insertAfter( currentRow ); // newRowInDomTree will be the element you created } 
+3
source

I think the effect you are looking for can be simplified by using the correct function:

instead:

 currentRow.after('<tr class="added-row"><td>This is new</td></tr>'); 

You must try:

 newRowInDomTree = $('<tr class="added-row"><td>This is new</td></tr>').insertAfter(currentRow); 

I would venture to suggest that your choice ( currentRow.next('tr') ) occurs before the element is actually added to dom. You can try listening to the onload or onreadystatechange onload to see if it will onreadystatechange later.

+1
source

How about how you do it?

 $(".existing-row a").click(function() { newRow = $(this).parent.after('<tr class="added-row"><td>This is new</td><tr>'); }); 
0
source

Give the identifier to the table. those.

 < table id="me"> var iHtml = ' < tr class="added-row">< td>This is new asdasdasd< /td>< /tr>' ; $('#me tr:last').after('iHtml '); 
0
source

All Articles