user3457337
user3457337

Reputation: 55

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.

Upvotes: 1

Views: 186

Answers (4)

Rounin
Rounin

Reputation: 29453

An id is for a single, unique element on the page.

Consequently, fishToLeft and fishToRight are not ids but classes.

So, you need to use:

<div class="fishToLeft"></div>
<div class="fishToRight"></div>

Later, when you want to want to select all the fish, you can use:

var fishesToLeft = document.getElementsByClassName('fishToLeft'); 
var fishesToRight = document.getElementsByClassName('fishToRight'); 

Upvotes: 0

MrCode
MrCode

Reputation: 64526

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(){

});

Upvotes: 1

Abhishek Dhanraj Shahdeo
Abhishek Dhanraj Shahdeo

Reputation: 1356

Try this:

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

Let's say you want it on click event, then:

$(".fish").on("click", function(){
    var myFish = $(this);
})

myFish will contain the clicked element

Upvotes: 0

Developer
Developer

Reputation: 6430

Problem with this code is that you have multiple elements with the same id which is wrong. I would use class or custom attributes instead. Eg, with class selector:

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

$newfish.appendTo('#sea'); 

var $fishesToLeft = $(".fishToLeft"); // array of elements/fishes to left

Upvotes: 0

Related Questions