Home > database >  How to duplicate element content using onclick in jquery or JS
How to duplicate element content using onclick in jquery or JS

Time:12-14

Every time i clicked on any h5 tag it always insert the first h5 which is "First Trial" in below example, i need to print the rest of tags if clicked on it carrying the same class or ID if needed to add.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h5  style="cursor: pointer;">First Trial</h5>
<h5  style="cursor: pointer;">Second Trial</h5>
<h5  style="cursor: pointer;">Third Trial</h5>
<h5  style="cursor: pointer;">Fourth Trial</h5>
<h5  style="cursor: pointer;">Fifth Trial</h5>
<h4 ></h4>


<script>
  $('.trial').click(function() {
    $('.final').html($('.trial').html());
  });
</script>

CodePudding user response:

Just for the completeness a plain JavaScript solution for those, who don 't want a dependency to jQuery or just want to get rid of jQuery in 2021.

let elements = document.querySelectorAll('.trial'),
    container = document.querySelector('.final');

elements.forEach(element => element.addEventListener('click', event => {
    container.append(event.currentTarget.cloneNode(true));
}));
<h5  style="cursor: pointer;">First Trial</h5>
<h5  style="cursor: pointer;">Second Trial</h5>
<h5  style="cursor: pointer;">Third Trial</h5>
<h5  style="cursor: pointer;">Fourth Trial</h5>
<h5  style="cursor: pointer;">Fifth Trial</h5>
<h4 ></h4>

This snippet adds an event listener to every h5.trial element. You should avoid that. Better practice: Add a single event listener to a parent element, that contains the elements you want to observe.

CodePudding user response:

You can get the element which has click by $(this) in your event handler, Then make clone of clicked element and append it to the .final element, like this:

$('.trial').click(function() {
  $('.final').append($(this).clone())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h5  style="cursor: pointer;">First Trial</h5>
<h5  style="cursor: pointer;">Second Trial</h5>
<h5  style="cursor: pointer;">Third Trial</h5>
<h5  style="cursor: pointer;">Fourth Trial</h5>
<h5  style="cursor: pointer;">Fifth Trial</h5>
<h4 ></h4>

If you want to allways show just last element which has clicked, you can change your script like this:

$('.trial').click(function() {
  $('.final').html($(this).clone())
});
  • Related