James
James

Reputation: 2964

how to copy the content of a div to another div

I'm trying to copy the single element inside a selected div to another div with jquery. But with my code copies entire division to another division..

My code is :

$('#image').html($('#selected').html());  //which copies entire content of #selected division

And the division is:

<div class="imgs" id="selected">
<img width="100%" height="100%" data-id="1" data-alid="1" src="data:image/jpeg;base64,">
<div class="xyz"><a href="#">Xyz</a></div>
</div>

I need to copy only the img from the div imgs

Please anyone help me ... Thanks....

Upvotes: 0

Views: 1745

Answers (3)

MG_Bautista
MG_Bautista

Reputation: 2653

Use this...

$('#image').html($('#selected').innerHTML());

Upvotes: 0

Evan
Evan

Reputation: 6115

are you looking to select the img from the #selected div?

if so just do

$('#image').html($('#selected img').html()); 

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074335

Here's an example that makes a copy of the first img element inside the element with the id "selected" and appends it to an element with the id "image":

$("#selected > img").first().clone().appendTo("#image");

That uses:

  • $() to find all img elements that are direct children of the element with the id "selected"

  • first() to reduce that to just the first matching img

  • clone to clone (copy) it

  • appendTo to append it to the element with the id "image"


It's well worth spending an hour reading through the jQuery API docs beginning to end. It's amazing how much time that will save you in the long wrong.

Upvotes: 4

Related Questions