DdD
DdD

Reputation: 612

Jquery .find doesn't look into the father element

I was trying to clone and change all the ids of a line in a table following the answer https://stackoverflow.com/a/2977114/327247 but the code below doesn't change the first id: the row id. The javascript is

 var $clone = $("#RowPly-R1-P1");
 $clone.find('[id]').each(function() {
   var $th = $(this);
   var newID = $th.attr('id').replace(/-P\d+$/,
                                    function(str) { return "-P"+i; });
   console.log(newID);
   $th.attr('id', newID);
 });
 console.log($clone);
 $clone.appendTo($tableToModfiy);
 $clone.after($("RowPly-R1-P1"));

while the html is

<tbody id="tblPlayers">
 <tr id="RowPly-R1-P1">
 <td>1</td>
 <td>
   <div class="input-group">
   ............
   </div>
  </td>
  </tr>                                 
</tbody>

All the ids internal to the row are successfully changed.I cannot understand why find doesnt change the first ID.

Upvotes: 0

Views: 38

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Because .find() will find all the descendant elements of the clone element, not the clone element itself so the ID of the clone element is not updated.

$clone.find('[id]').addBack()

You can also try a attr('id', callback) format like

var $clone = $("#RowPly-R1-P1");
$clone.find('[id]').addBack().attr('id', function(i, id) {
  return id.replace(/-P\d+$/,
    function(str) {
      return "-P" + i;
    });
});

Upvotes: 1

Related Questions