Jquery html change on clone

When I click, I copy the div. I want to change some html and then add.

I tried the following: it will clone and add, but I cannot change the html. Not sure if this is the best way to handle this, I'm sure I'm wrong.

thanks

var htmlStr = $(this).parents(".listingContainer").first(); $htmlStr.find(".saveCompareShow").remove() $(htmlStr).clone().appendTo('.compareWrapper'); 
+4
source share
3 answers

Once you have cloned a DOM element, you should treat it the same way as if you wanted to modify a DOM element that is not cloned. You just use your variable instead of a selector.

Assuming you have HTML:

 ​<div class='listingContainer'> <div class='listing'> Something </div> <div class='listing'> Another something </div> </div> 

You can clone the contents of the Container DIV listing and modify the contents before adding them to the compareWrapper div. The following JavaScript example shows a simple example:

 $(document).ready(function() { $('.listing').click(function() { var $htmlStr = $(this).parents(".listingContainer").first(); $htmlStr.clone().find('.listing').html('<li>Cloned</li>').appendTo('.compareWrapper'); }); }); 

I also posted jsFiddle so you can see it working: http://jsfiddle.net/hkBMK/

+7
source

After cloning, you can process the object in the same way as if it were html already in dom.

For example - html on your page:

 <div id="cloneHere"></div> <div class="well" id="buildInfoTemplate"> <form> <fieldset> <legend></legend> <label></label> <input type="text" placeholder="Type something…"> <span class="help-block">Example block-level help text here.</span> <button class="btn">Save</button> </fieldset> </form> </div> 

Suppose you wanted to change the text of a help block:

 var template = $('#buildInfoTemplate').clone().removeAttr('id'); $('.help-block',template).html('hi there ryan'); $('#cloneHere').append(template); 

And you will get:

 <div id="cloneHere"> <div class="well"> <form> <fieldset> <legend></legend> <label></label> <input type="text" placeholder="Type something…"> <span class="help-block">hi there ryan</span> <button class="btn">Save</button> </fieldset> </form> </div> </div> 
+1
source

so your htmlStr variable is actually an element, not a string. but it normal. I think you need to do this on the second line:

 htmlStr.remove(".saveCompareShow"); 

If I see correctly, you are trying to remove elements with the class .saveCompareShow from the htmlStr element. Is it correct?

** EDIT **

Try replacing both lines 2 and 3

 $(htmlStr).clone().remove(".saveCompareShow").appendTo('.compareWrapper'); 
0
source

Source: https://habr.com/ru/post/1400402/


All Articles