How to create a new img tag using jQuery, with src and id from a JavaScript object?

I understand jQuery in the main sense, but I'm definitely new to this, and I suspect it is very easy.

I have an src image and image id in a JSON response (converted to an object) and therefore the correct values ​​in responseObject.imgurl and responseObject.imgid, and now I would like to create an image with it and add it to the div (let's call it <div id="imagediv"> ). I am a little fixated on dynamic construction <img src="dynamic" id="dynamic"> . Most examples I've seen include replacing src with an existing image, but I don't have an existing image.

+70
javascript jquery image
Nov 04 '11 at 18:01
source share
4 answers

In jQuery, a new element can be created by passing an HTML string to the constructor, as shown below:

 var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img')) img.attr('src', responseObject.imgurl); img.appendTo('#imagediv'); 
+109
Nov 04 '11 at 18:03
source share
 var img = $('<img />', { id: 'Myid', src: 'MySrc.gif', alt: 'MyAlt' }); img.appendTo($('#YourDiv')); 
+74
Nov 04 '11 at 18:11
source share

You save a few bytes while avoiding .attr by passing properties to the jQuery constructor:

 var img = $('<img />', { id: 'Myid', src: 'MySrc.gif', width: 300 }) .appendTo($('#YourDiv')); 
+12
Jun 08 '13 at 15:09
source share

For those who need the same function in IE 8, I solved this problem:

  var myImage = $('<img/>'); myImage.attr('width', 300); myImage.attr('height', 300); myImage.attr('class', "groupMediaPhoto"); myImage.attr('src', photoUrl); 

I could not get IE8 to use the object in the constructor.

+2
May 06 '14 at 11:04
source share



All Articles