Getting inserted jQuery DOM elements without query for an element after insertion

Assuming I embed something in my DOM with jQuery , for example:

$('#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 additional search, for example

 var myImage = $('#someselector #someid'); 

???

+6
source share
3 answers

You can try something like this:

 $('#someselector') .prepend('<img src="/img/myimage.gif" id="someid" />') .find('#someid'); 

Or if there is only one img:

 $('#someselector') .prepend('<img src="/img/myimage.gif" id="someid" />') .find('img'); 

As an alternative:

 $('<img src="/img/myimage.gif" id="someid" />').prependTo('#someselector') 
+5
source

Add it to the jQuery object before adding it:

 var $img = $('<img src="/img/myimage.gif" id="someid" />'); $('#someselector').prepend($img); $img.foo(); 
+11
source

Solution without creating a jQuery object before and without Id:

 var $img = $('#someselector') .prepend('<img src="/img/myimage.gif" />') .find(':first'); 
+1
source

Source: https://habr.com/ru/post/887715/


All Articles