Jason Mort
Jason Mort

Reputation: 69

How to add HTML templates in a page?

I made an template of a price box, and I want that every time that I click a button a new price box shows up in the page. Just a simple example for my template:

<div>
  <h1> Product: {productName} </h1>
</div>

And everytime that I click a button, I pass the name and this template will show in the page.

I was looking and I saw the template tag with javascript and another solutions like Mustache. Which approach would be better and more readable?

Upvotes: 0

Views: 213

Answers (1)

Cory Kleiser
Cory Kleiser

Reputation: 2024

Not exactly sure what your asking but this would be very simple using pure javascript. Please see the following code snippet:

function addProduct() {
  const productName = document.querySelector('#productName').value;
  productName ? document.querySelector('#products').innerHTML += `
<div><h1>Product: ${productName}</h1></div>
` : alert('Enter Product Name');
}

document.querySelector('#add').addEventListener('click', () => addProduct());
<input type="text" id="productName">
<button id="add">Add Product</button>
<div id="products"></div>

Upvotes: 1

Related Questions