JQuery nth-child selector not working

I have div id (auctions) and I want to change the HTML code with the children of the auction list. However, jQuery cannot select children of the auction div list.

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 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 Javascript warnings:

First warning

 2 

Second warning

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

Third Alert

 null 

What am I not seeing here?

+4
source share
5 answers

You need space between your selectors, for example:

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

With your selector, it searches for the #auction-list item, which is the 1st child of another item, when you are really looking for an item that is the nth child list.

+19
source

I do not think you should use the :nth-child selector for the element id. It must be a classified item.

as

 alert($("div.auction-item:nth-child(1)").html()); 
+2
source

Try the following:

 $("#auction-list > .auction:nth-child(2)") 

Take a look at the docs . You are trying to select the nth element of #auction-list instead of your children.

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

I had a problem where the click event could fire in IE and chrome but not firefox. I forgot the typo. I thought I would share that it would help someone.

  $(document).ready(function () { $(".test table tr:nth-child(1n+2").click(function () { alert(this.id); }); }); 

I was missing) after +2.

JSFiddle: https://jsfiddle.net/xv3bca60/7/

0
source

All Articles