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

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


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'));


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'));