Search code examples

Defining a HTML template to append using jQuery

I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the HTML code below to a container element with some values.

Where can I put this HTML to re-use in a smart way?

<a href="#" class="list-group-item">
    <div class="image">
         <img src="" />
    <p class="list-group-item-text"></p>


$('.search').keyup(function() {

    $.each(items, function(index) {


  • You could decide to make use of a templating engine in your project, such as:

    If you don't want to include another library, John Resig offers a jQuery solution, similar to the one below.

    Browsers and screen readers ignore unrecognized script types:

    <script id="hidden-template" type="text/x-custom-template">

    Using jQuery, adding rows based on the template would resemble:

    var template = $('#hidden-template').html();
    $('button.addRow').click(function() {