Jump to content

jquery nth-child()


The Little Guy

Recommended Posts

I have this jquery that isn't working. It is a search box. When someone searches for something a list of suggestions shows. When they press down it is supposed to go to the first result, down again another result, and so on. The problem I am having is when someone presses down the first time it selectPos is 1, it doesn't go to the first suggest-item, it goes to the first div. press down again selectPos is now 2 and it doesn't go to the second suggest-item but the second div. This continues up till 5 and starts over (which it should do).

 

so, why is it going to the nth div and not the nth suggest-item?

 

The jquery:

$("div#suggest div.suggest-item:nth-child("+(selectPos)+")").addClass("suggest-hover");

 

The HTML:

<div id="suggest" style="display: none; ">
<div class="suggest-header">
	<div class="suggest-strike"></div>
	<div class="suggest-head">SNIPPETS</div>
</div>
<div class="suggest-nomatch">No Matches Found</div>
<div class="suggest-header">
	<div class="suggest-strike"></div>
	<div class="suggest-head">PEOPLE</div>
</div>
<div class="suggest-item" id="people_886">imPathpaif</div>
<div class="suggest-item" id="people_1367">perybrirur</div>
<div class="suggest-item" id="people_4093">Meectireen</div>
<div class="suggest-item" id="people_111522">TotEsopsyZ</div>
<div class="suggest-item" id="people_111560">fluffZoorn</div>
</div>

Link to comment
https://forums.phpfreaks.com/topic/261198-jquery-nth-child/
Share on other sites

:nth-child() doesn't work like that. From the documentation (which says it better than I could):

 

With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class.

 

You want this:

 

$("div#suggest div.suggest-item:eq("+(selectPos)+")").addClass("suggest-hover");

 

However, be warned that unlike :nth-child(), :eq() starts its index at zero, so you will probably have to alter your code for that.

Link to comment
https://forums.phpfreaks.com/topic/261198-jquery-nth-child/#findComment-1338788
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.