简体   繁体   中英

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....

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.

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

if so just do

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

用这个...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM