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.
With jQuery, you can dynamically create a new image element and append it at the end of the DOM container using the . append() method. This is demonstrated below: jQuery.
Definition and UsageThe required src attribute specifies the URL of an image. Note: The src property can be changed at any time. However, the new image inherits the height and width attributes of the original image, if not new height and width properties are specified.
Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.
Example: src="img_girl. jpg". If the URL begins with a slash, it will be relative to the domain. Example: src="/images/img_girl.
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With