Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone element with class

Tags:

jquery

How to clone content of the element with class and put it into itself?
Here is example. We have this:

<div class="cloneThis">one</div>
<div class="cloneThis">two</div>

The result must be like

<div class="cloneThis">one<span>one</span></div>
<div class="cloneThis">two<span>two</span></div>

I tried something like

$('.cloneThis', this).append('<span>'+$('.cloneThis', this).html()+'</span>');

but it returns first element of class and put it into all other. Is there any way to solve this?

like image 730
elrocie Avatar asked Sep 06 '26 05:09

elrocie


2 Answers

$('.cloneThis', this).each(function() {
 $(this).append('<span>' + $(this).html() + '</span>');
});
like image 200
alex Avatar answered Sep 07 '26 20:09

alex


.append() takes a function, like this:

$('.cloneThis').append(function(i, html) { return $('<span>').html(html); });
//or:
$('.cloneThis').append(function(i, html) { return $('<span>', { html:html }); });

You can test it out here.

like image 27
Nick Craver Avatar answered Sep 07 '26 21:09

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!