Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery nth-child selector not working

I have a div id (auctions), and I want to swap out the HTML with the children of auction-list. However, jQuery cannot select the children of the auction-list div.

Here's the HTML:

<div id="all">      
    <div id="auctions"></div>
</div>

<div id="auction-list" class="hide">
    <div class="auction">Test</div>
    <div class="auction">Test</div>
</div>

Here's the jQuery:

alert($("#auction-list").children().length);
alert($("#auction-list").html());
alert($("#auction-list:nth-child(1)").html());
alert($("#auction-list:nth-child(2)").html());
$("#auctions").html($("#auction-list:nth-child(1)").html());

And here are the outputs for the Javascript alerts:

First Alert

2

Second Alert

<div class="auction">Test</div>
<div class="auction">Test</div>

Third Alert

null

What am I overlooking here?

like image 233
Jarred Avatar asked Jul 25 '11 21:07

Jarred


Video Answer


2 Answers

You need a space between your selectors, like this:

alert($("#auction-list :nth-child(1)").html());
//                    ^-- Space here

With your selector, it's looking for the element #auction-list, which is a the 1st child of another element, when what you're actually looking for an element that is the nth child of the list.

like image 85
Karl Nicoll Avatar answered Oct 17 '22 05:10

Karl Nicoll


I don't think you should be using the :nth-child selector on an element id. It should be a classed item

like;

alert($("div.auction-item:nth-child(1)").html());
like image 44
Orson Avatar answered Oct 17 '22 04:10

Orson