user3457337 user3457337 - 1 year ago 67
Javascript Question

How to select an appended element?

I'm experimenting with jQuery & Javascript. I'm trying to create an interactive sea with fishes etc.

I'm randomly placing fish div's on the page at random positions with the following code:

$newfish = $("<div id='fishToLeft'></div>").css({
'left': randomX + 'px',
'top': randomY + 'px',


The images of the fish are configured in the CSS.

Now I want to animate those divs (it appends around 20 fish), but I can't figure out how to select the appended fish divs (fishToLeft & fishToRight).

Can anyone help me?

SOLVED! Instead of using the same id for all the fishes, I used the same class, now it works.

Thanks for all the quick answers.

Answer Source

Use a class not an id, because ids should be unique.

$newfish = $("<div class='fish'></div>").css({

Select by class:


Alternatively, if only fish exist as children, then just select children:


By storing the fish references in an array, you can avoid re-selecting them:

var fish = [];
// in your loop

Do something with each fish:

$.each(fish, function(){

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download