omer Farooq omer Farooq - 1 month ago 7
HTML Question

How to modify parts of an element, when its inside a variable

The original div is pretty large, so basically here is a trimmed down version. I have a div that i clone into another div, every time a button is pressed.

<div id="demo_variation">
<div>
<h4 class="panel-title">
<span class="title">Product Variation</span>
</h4>
</div>
</div>

<div id="all_variations">

</div>


Now when someone clicks a button i want to clone #demo_variation into #all_variation but also need to change things like id and title.
Ideally what i want is to do something like this.

var newVariation = $('#demo_variation').html();
newVariation.find('#demo_variation').attr('id', 'product_variation_1');
newVariation.find('.title').text('Product Variation 1');


But for some reason this doesn't work. Am i doing this wrong??

Answer

You can use clone() like this:

var count = 0;
$('button').on('click',function(){
  var cont=$('#demo_variation').clone().prop('id','new'+count);
  $('#all_variations').append(cont);
  $('#all_variations .title').last().text('New Title'+count)
  count++;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="demo_variation">
    <div>
        <h4 class="panel-title">
           <span class="title">Product Variation</span>
        </h4>
    </div>
</div>

<div id="all_variations">
</div>
<button>Append New</button>