rockie667 rockie667 - 5 months ago 24
jQuery Question

JQuery: Create image and div and then append image to div

I want to create an image object, then a div object, append the image to the div and finally append the result to a wrapper.

I did this:

var image = $(document.createElement('img'));
image.attr('src', url);
image.attr('id', 'preview_gallery_image_' + i);
image.addClass('admin-hotel-gallery-image');
var imageDiv = $(document.createElement('div'));
imageDiv.addClass('col-sm-3');
imageDiv.attr('id', 'preview_gallery_image_wrapper_' + i);
var imageNode = image.appendTo(imageDiv);
var finalElement = imageNode.appendTo("#gallery-wrapper");


To make it a bit clearer, the final result should look like this:

<div id="gallery-wrapper>
<div class="col-sm-3" id="preview-gallery-image-wrapper-1">
<img url="...">
</div>
</div>


What I get is only the image in the gallery wrapper, but the inner imageDiv around the image is missing:

<div id="gallery-wrapper>
<img url="...">
</div>


What am I doing wrong?

Answer

DEMO LINK

js code

var url = 'url';
var i =1 ;

var image = $('<img />', { 
 id:'preview_gallery_image_' + i,
 class: 'admin-hotel-gallery-image' ,
 src: url
});

var imageDiv = $('<div >',{
  id: 'preview_gallery_image_wrapper_' + i
});

image.appendTo(imageDiv);



var finalElement = $('<div/>',{
  id: 'gallery-wrapper' 
});

imageDiv.appendTo(finalElement);
finalElement.appendTo('body');

result:

<div id="gallery-wrapper">
    <div id="preview_gallery_image_wrapper_1">
        <img src="url" class="admin-hotel-gallery-image" id="preview_gallery_image_1">
    </div>
</div>
Comments