1

How can I copy the whole <img /> using jquery.

At the moment I am trying: $('img').clone().html()

Usage:

'<div class="content-left">'+$(this).find(".bar .info").html()+$(this).find(".bar img").clone().html()+'</div>';
John Magnolia
  • 16,769
  • 36
  • 159
  • 270

3 Answers3

4

To create new copies of every image in the DOM you can select them and clone them, then append them to some container.

//store a clone of all the images in the DOM in a variable
var $clone = $('img').clone();

//now add the clones to the DOM
$('#newContainer').html($clone);

Here is a demo: http://jsfiddle.net/jasper/r3RDx/1/

Update

You can create your HTML like this:

//create a new element to add to the DOM
//start by creating a `<div>` element with the `.content-left` class
//then add a string of HTML to this element
//then append a set of DOM elements (clones) to the same parent element (the `<div>`)
var $newElement = $('<div />').addClass('content-left').html($(this).find('.bar .info').html()).append($(this).find('.bar img').clone());

//then you can add the new element(s) to the DOM
$newElement.appendTo('#newContainer');

Here is a demo: http://jsfiddle.net/jasper/r3RDx/2/

Community
  • 1
  • 1
Jasper
  • 75,717
  • 14
  • 151
  • 146
1

jQuery objects are simple arrays containing the html of the selected element. This means that I can simply do: $('img.someclass')[0] to access the html of the first (and probably only) matched element.

Alexander Varwijk
  • 2,075
  • 18
  • 21
0

clone includes the event handlers of the object. If you want just the html whats below would be fine

    $('#someid').html($('img'))
useful
  • 472
  • 3
  • 6
  • This just outputs: [object Object] – John Magnolia Feb 24 '12 at 21:21
  • That actually has the effect of moving all of the images selected to the new container. So instead of creating copies, this will just move the DOM elements from one container to another... which can be useful if it's the behavior you want. Also you can set whether or not you want to copy event handlers: http://api.jquery.com/clone/ – Jasper Feb 24 '12 at 21:26
  • Try this then $('img').each(function(index, value) { console.log(value.outerHTML) }); – useful Feb 24 '12 at 21:37