Search code examples
javascriptjqueryhtmlajaxjquery-load

Append loaded HTML multiple times


I have a section of HTML located in a separate file that I wish to load into the current page and append multiple times to a div.

Any combination of for and append and clone appear to only append one instance of the HTML.

External HTML

<article class="article">
    <section class="section">
        <h1>Title</h1>
    </section>
</article>

jQuery

function loadContent() {
    var instances = 2;
    var list = $('<section id="list-view">');
    var downloads = $('#downloads');

    downloads.empty();
    list.load('filename.html .card', function() {
        for (var i = 0; i < instances; i++) {
            downloads.append(list);
        }
    });
}

loadContent();

HTML

<article id="downloads"></article>

Result I'm trying to achieve

<article id="downloads">
    <section id="list-view">
        <article class="article">
            <section class="section">
                <h1>Title</h1>
            </section>
         </article>
         <article class="article">
            <section class="section">
                <h1>Title</h1>
            </section>
         </article>
         <article class="article">
            <section class="section">
                <h1>Title</h1>
            </section>
         </article>
    </section>
</article>

Solution

  • I would use regular $.get() to fetch the external HTML, and then in loop append it:

    $.get("filename.html").then(function(data) {
      $(data).find(".card").each(function() {
        downloads.append(this.innerHTML)
      })
    })