6

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

???

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Sorcy
  • 2,587
  • 5
  • 26
  • 34

3 Answers3

11

Make it into an jQuery object before prepending it:

var $img = $('<img src="/img/myimage.gif" id="someid" />');    
$('#someselector').prepend($img);    
$img.foo();
Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185
5

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')
qwertymk
  • 34,200
  • 28
  • 121
  • 184
1

Solution without creating a jQuery object before and without having an Id:

var $img = $('#someselector')
            .prepend('<img src="/img/myimage.gif" />')
            .find(':first');    
Marc
  • 6,749
  • 9
  • 47
  • 78