Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 747
Peter Avatar asked Nov 04 '11 18:11

Peter


People also ask

How can add image in HTML using jQuery?

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.

What is IMG src in JavaScript?

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.

How add src attribute in jQuery?

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.

How do I make an image src?

Example: src="img_girl. jpg". If the URL begins with a slash, it will be relative to the domain. Example: src="/images/img_girl.


2 Answers

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'); 
like image 165
Rob W Avatar answered Sep 22 '22 06:09

Rob W


var img = $('<img />', {    id: 'Myid',   src: 'MySrc.gif',   alt: 'MyAlt' }); img.appendTo($('#YourDiv')); 
like image 40
Frenchi In LA Avatar answered Sep 23 '22 06:09

Frenchi In LA