Daniel Peñalba
Daniel Peñalba

Reputation: 31857

jQuery: add row to table and the select it in DOM

I want to add a row to a table, and then use it as a DOM object. Suppose 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 use the following JavaScript with jQuery to insert a row:

  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 a tr.existing-row instead a tr.added-row. It seems that the DOM tree is not updated, but I don't undertand why.

Any ideas?

Upvotes: 4

Views: 2223

Answers (4)

cmani
cmani

Reputation: 979

Give an id to the table. ie,

< table id="me">

var iHtml = ' < tr class="added-row">< td>This is new asdasdasd< /td>< /tr>' ;

$('#me tr:last').after('iHtml ');

Upvotes: 0

halfpastfour.am
halfpastfour.am

Reputation: 5933

How about you just do it like this?

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

Upvotes: 0

zzzzBov
zzzzBov

Reputation: 179086

I think the effect you're looking for can be simplified by using the right function:

instead of:

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

you should try:

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

I'd venture a guess that your selection (currentRow.next('tr')) is happening before the element is actually added to the dom. You could try listening for an onload or onreadystatechange event to see if it's being fired later.

Upvotes: 1

user113716
user113716

Reputation: 322502

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

An alternative would be to retain a reference to the new element when creating it. 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
}

Upvotes: 3

Related Questions