prettyInPink
prettyInPink

Reputation: 3444

jQuery, remove all instances with class from cloned element

Trying to remove with jQuery all selectors with a specific class from a cloned element with children. Original markup:

<div id="el">
  <div class="remove">remove from clone</div>
  <div class="remain">remain in clone</div>
  <div class="remove">remove from clone</div>
  <div class="remain">remain in clone</div>
  <div class="remove">remove from clone</div>
  <div class="remain">remain in clone</div>
</div>

Cloned version should look like this:

<div id="el">
  <div class="remain">remain in clone</div>
  <div class="remain">remain in clone</div>
  <div class="remain">remain in clone</div>
</div>

jQuery code (not working for my purpose):

var clone = $('#el').clone();
clone = $(clone).remove('.remove');
clone = clone.html();
console.log(clone);

When I log to see if the remove elements exists in the clone, it puts out the correct number:

console.log($(clone).find('.remove').length);

Anyone can help on this. Thanks so much! (possible duplicate though)

Upvotes: 1

Views: 1056

Answers (2)

charlietfl
charlietfl

Reputation: 171669

The problem is $(clone).remove('.remove');

This is suggesting remove the cloned element if it has the class remove

You need to use find() since that class is nested inside the element

var clone = $('#el').clone();
clone.find('.remove').remove();
clone = clone.html();
console.log(clone);

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

Your usage of remove() isn't quite right as the selector you provide is used to filter the current set of elements, not find within them.

To achieve what you require you need to use find() then remove() separately, like this:

var $clone = $('#el').clone();
$clone.find('.remove').remove();
var clone = $clone.html();
console.log(clone);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="el">
  <div class="remove">remove from clone</div>
  <div class="remain">remain in clone</div>
  <div class="remove">remove from clone</div>
  <div class="remain">remain in clone</div>
  <div class="remove">remove from clone</div>
  <div class="remain">remain in clone</div>
</div>

Upvotes: 4

Related Questions