How to create a new img tag with JQuery, with the src and id from a JavaScript object?
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.
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');
var img = $('<img />', {
id: 'Myid',
src: 'MySrc.gif',
alt: 'MyAlt'
});
img.appendTo($('#YourDiv'));