简体   繁体   中英

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.

$(".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>

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM