Alireza Farahani
Alireza Farahani

Reputation: 2539

Select an element from dynamicaly appended childs

I have a div which it's content updates by receiving new data from ajax. I remove old content and append new data to the div. The problem is when I cant select a child that has appended to div.

Here's my code:

<div id="page-container" style="width: 55px;"> //div I want to update contents
     <div class="page-div">1</div> // appended childs
     <div class="page-div">2</div>
</div> 

these lines doesn't work:

$("#page-container:nth-child(2)")
$("#page-container").eq(1)

Do you guys know what's the problem?

Upvotes: 0

Views: 36

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

you need

$("#page-container > :nth-child(2)")

or

$("#page-container > :eq(1)")
$("#page-container").children(':eq(1)')
$("#page-container").children().eq(1)

Note: You need to execute these selectors only after the children are appended

#page-container:nth-child(2) looks for an element with id page-container which is the second child of its parent

$("#page-container").eq(1) looks for an element with id page-container which is at index 1 which will never be there because the id selector will always return 1 element

Upvotes: 1

Related Questions