Sorcy
Sorcy

Reputation: 2613

Getting jQuery-inserted DOM elements without requerying for element after insertion

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

Answers (3)

Marc
Marc

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

qwertymk
qwertymk

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

Tatu Ulmanen
Tatu Ulmanen

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

Related Questions