user3457337 user3457337 - 27 days ago 6
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',
})

$newfish.appendTo('#sea');


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

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

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

Select by class:

$('.fish');

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

$('#sea').children();

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

var fish = [];
// in your loop
fish.push($newfish);

Do something with each fish:

$.each(fish, function(){

});