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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.