简体   繁体   中英

Clone an html element one too many times

I am attempting to clone an HTML <select> dropdown one to many times, given a json response.

The issue is that when I attempt to store the clone in a variable and display it on the screen all I see is the following:

[object Object]

I made a simple JSFIDDLE to help explain my issue.

Things to note:

The select dropdown is in a hidden div.

<div class="hidden">
    <select class="certList">
       .....
    </select>
</div>

I am building a string using:

buildList += "<div....

I then append the list I build using the jQuery append function.

$("#certRow").append(buildList);

Lastly if there are any tips to how I should display the results better I am all ears. I was thinking on using an unordered list but wasn't sure how to.

Copy the html into your append string:

"<div class='col-4'>"+certList[0].outerHTML+"</div></div>";

As it stands your concatenating a string with the jQuery object (And object.ToString() is [object Object] )

append the element to the div

    var certList = $(".certList").clone();
    var buildList = "";
      $.each(res.data, function(i, data) { 
        buildList += "<div class='ti-row'>"+
            "<div class='col-4 center'>"+data +"</div>"+
            "<div class='col-4 right'>Select Certs : </div>"+
            "<div class='col-4 addSelect'></div></div>";
        });
        var html = $(buildList);
        html.find(".addSelect").append(certList);    
        $("#certRow").append(html);

Try using outerHTML

var certList = $(".certList")[0].outerHTML;

Updated Fiddle

Use .parent().html() instead of .clone()

clone returns object and you can't append object to string but html returns string that you can append

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM