Getting jQuery-inserted DOM elements without reque

2020-04-05 08:25发布

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

???

3条回答
▲ chillily
2楼-- · 2020-04-05 09:12

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')
查看更多
对你真心纯属浪费
3楼-- · 2020-04-05 09:13

Make it into an jQuery object before prepending it:

var $img = $('<img src="/img/myimage.gif" id="someid" />');    
$('#someselector').prepend($img);    
$img.foo();
查看更多
三岁会撩人
4楼-- · 2020-04-05 09:27

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

var $img = $('#someselector')
            .prepend('<img src="/img/myimage.gif" />')
            .find(':first');    
查看更多
登录 后发表回答