user969729
user969729

Reputation: 299

Jquery clone a table with specific row class

Hey how can I clone the table named teamselectiontable with just the table rows that have the class "chosen", and modify another table and replace its contents with the table rows found. But keeping the class names of "row" in the appended table.

<table id="teamselectiontable">
  <tr class="chosen">content</tr>
  <tr class="something">content</tr>
  <tr class="something">content</tr>
  <tr class="something">content</tr>
  <tr class="something">content</tr>
  <tr class="chosen">content</tr>
  <tr class="chosen">content</tr>
</table>

To a table like below.

<table id="talentselection">
  <tr class="row"></tr>
  <tr class="row"></tr>
  <tr class="row"></tr>
</table>

Thanks for any help.

Upvotes: 0

Views: 1872

Answers (2)

Michal
Michal

Reputation: 13649

$(".chosen").clone().attr("class","row").appendTo("#talentselection")

or if you want to replace the whole contents of the target table

$("#talentselection").html($(".chosen").clone().attr("class","row"));

Please note you need tds in your table markup for this to work

<tr><td class="chosen">content</td></tr>

Upvotes: 1

James Allardice
James Allardice

Reputation: 166021

Assuming I've understood what you're trying to do, you can use the clone method to clone the selected elements, and the appendTo method to append the clones into another element:

$("#teamselectiontable .chosen").clone().appendTo("#talentselection");

The elements in the original selection will be unaffected. Note that in its current form the above code will not clone any events bound to the matched elements. If you wanted to clone the elements with their events, just pass true into the clone method.

Update (see comments)

To change the class name on the cloned elements, you can use the removeClass and addClass methods:

$("#teamselectiontable .chosen")
    .clone()
    .appendTo("#talentselection")
    .removeClass("chosen")
    .addClass("row");

Upvotes: 0

Related Questions