Kyle Underhill
Kyle Underhill

Reputation: 109

Creating multiple identical elements in jQuery

I want to be able to create a new item which will essentially have the same structure of all of the other items in the same list. I have looked into append but I'm wondering if there is an easier way than writing out my structure using append.

In a perfect world I could duplicate the last li in a ul on click of a create button and have a new element added to the DOM that is an exact copy of the last ul child (less any of the information that might be in the last item).

OR maybe I could have a dummy element already created and each time the user clicks the create button a new instance of this dummy is added?

Any guidance is greatly appreciated!

Upvotes: 1

Views: 146

Answers (3)

Maarten Bicknese
Maarten Bicknese

Reputation: 1548

Have you looked into the HTML5 template element?

The HTML Content Template () element is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaScript.

-- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template

You can get the content and use jQuery to create a new element from it.

$('#add').click(function() {
  $('#list').append($('#new-li').html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<template id="new-li">
  <li>
    Hello World!
  </li>
</template>

<ul id="list">

</ul>

<button type="button" id="add">+ NEW</button>

Upvotes: 2

Sakata Gintoki
Sakata Gintoki

Reputation: 1825

It may easy to do, please check my code snipet bellow:

var listEl = $('.list');
$('.create-btn').on('click', function() {
  var lastItemNode = listEl.find('li:last-child').clone();
  listEl.append(lastItemNode);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ul>

<button class="create-btn">Create new item</button>

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370639

You can use .clone on the last element:

$('div').on('click', () => {
  $('ul').append($('ul > li:last-child').clone())
});
.li-class {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>click</div>
<ul>
<li class="li-class">li text here</li>
</ul>

Upvotes: 1

Related Questions