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

JavascriptJqueryImage

Javascript Problem Overview


I understand JQuery in the basic sense but am definitely new to it, and suspect this is very easy.

I've got my image src and id in a JSON response (converted to an object), and therefore the correct values in responseObject.imgurl and responseObject.imgid, and now I'd like to create an image with it and append it to a div (lets call it <div id="imagediv">. I'm a bit stuck on dynamically building the <img src="dynamic" id="dynamic"> - most of the examples I've seen involve replacing the src on an existing image, but I don't have an existing image.

Javascript Solutions


Solution 1 - Javascript

In jQuery, a new element can be created by passing a 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');

Solution 2 - Javascript

var img = $('<img />', { 
  id: 'Myid',
  src: 'MySrc.gif',
  alt: 'MyAlt'
});
img.appendTo($('#YourDiv'));

Solution 3 - Javascript

You save some bytes by avoiding the .attr altogether by passing the properties to the jQuery constructor:

var img = $('<img />',
             { id: 'Myid',
               src: 'MySrc.gif', 
               width: 300
             })
              .appendTo($('#YourDiv'));

Solution 4 - Javascript

For those who need the same feature in IE 8, this is how I solved the problem:

  var myImage = $('<img/>');

               myImage.attr('width', 300);
               myImage.attr('height', 300);
               myImage.attr('class', "groupMediaPhoto");
               myImage.attr('src', photoUrl);

I could not force IE8 to use object in constructor.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeterView Question on Stackoverflow
Solution 1 - JavascriptRob WView Answer on Stackoverflow
Solution 2 - JavascriptFrenchi In LAView Answer on Stackoverflow
Solution 3 - JavascriptErickBestView Answer on Stackoverflow
Solution 4 - JavascriptAmiga500View Answer on Stackoverflow