Search code examples
jqueryappendclone

how to append html to a cloned object


I have cloned some html and want to append some html before I append to parent div. How can I do that?

<div class="center">
    <div class="row-fluid">
        <div class="span3">
            <select class="chosen-select" id="form-field-select-3">
                <option value="">Text</option>
                <option value="AL">Department</option>
            <option value="AK">City</option>
                <option value="AZ">State</option>
                <option value="AR">Country</option>
                <option value="CA">Industry</option>
       </select>
        </div>
    </div>
</div>

JS Code:

var clone_search = $('.row-fluid .chosen-select').last().clone();
$('.center').append('<div class="row-fluid"><div class="span3">');
$('.center').append(clone_search);
$('.center').append('</div>');

Solution

  • It seems you want to wrap the cloned element with another element, you can use .wrap() method:

    $('.row-fluid .chosen-select')
         .last()
         .clone()
         .wrap('<div class="row-fluid"><div class="span3"/></div>')
         .appendTo('.center');
    

    note that you should change the ID of the cloned element otherwise your markup becomes invalid. Also why not cloning the div.row-fluid if you want to generate the same structure?

    $('.row-fluid').first()
                   .clone()
                   .find('.chosen-select')
                   .prop('id', 'something_else')
                   .end()  
                   .appendTo('.center');