Categories
JavaScript Answers

How to Define an HTML Template and Append it Using JQuery?

Spread the love

We can use the jQuery append method with a script tag that has its type set to a non-recognized type to add a template.

To do this, we can write:

<script id="hidden-template" type="text/x-custom-template">
  <tr>
   <td>Foo</td>
    <td>Bar</td>
  <tr>
</script>

<table id='targetTable'>

</table>

Then we can write:

const template = $('#hidden-template').html();
$('#targetTable').append(template);

to add the HTML in the script tag into the table element.

Since the type is set to text/x-custom-template which isn’t recognized by the browser, it won’t be parsed by it.

We get the HTML content of the script tag with the html method.

Then we can use append to append the HTML content.

Template String

Another way to add HTML to the DOM is to use template strings.

For instance, we can write:

<div class='list-items'>

</div>

Then we write:

const Item = ({ url, img, title }) => `
  <a href="${url}" class="list-group-item">
    <div class="image">
      <img src="${img}" />
    </div>
    <p class="list-group-item-text">${title}</p>
  </a>
`;
$('.list-items').html([
  { url: '/foo', img: 'https://i.picsum.photos/id/1/200/300.jpg?hmac=jH5bDkLr6Tgy3oAg5khKCHeunZMHq0ehBZr6vGifPLY', title: 'Foo item' },
  { url: '/bar', img: 'https://i.picsum.photos/id/1/200/300.jpg?hmac=jH5bDkLr6Tgy3oAg5khKCHeunZMHq0ehBZr6vGifPLY', title: 'Bar item' },
].map(Item).join(''));

We have the Item function that takes an object with the url , img , and title properties and put them into the template string that it returns.

Then we get the div with $(‘.list-items’) , and then call html with an array objects and map them to strings with a elements by calling map with Item .

And then we call join to join them strings together.

Now we see the items displayed on the page.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *