Reputation: 2613
Assuming I insert anything in my DOM with jQuery, like so:
$('#someselector').prepend('<img src="/img/myimage.gif" id="someid" />');
Is there a way in jQuery to get a jQuery
object referencing this new image, without having to do an extra search like
var myImage = $('#someselector #someid');
???
Upvotes: 6
Views: 3379
Reputation: 6771
Solution without creating a jQuery object before and without having an Id:
var $img = $('#someselector')
.prepend('<img src="/img/myimage.gif" />')
.find(':first');
Upvotes: 1
Reputation: 35284
You can try something like this:
$('#someselector')
.prepend('<img src="/img/myimage.gif" id="someid" />')
.find('#someid');
Or if there's only one img:
$('#someselector')
.prepend('<img src="/img/myimage.gif" id="someid" />')
.find('img');
Alternatively:
$('<img src="/img/myimage.gif" id="someid" />').prependTo('#someselector')
Upvotes: 5
Reputation: 124788
Make it into an jQuery object before prepending it:
var $img = $('<img src="/img/myimage.gif" id="someid" />');
$('#someselector').prepend($img);
$img.foo();
Upvotes: 11