timpone
timpone

Reputation: 19979

jQuery selector for a specific li

I have the following markup

<div id="search-query-autocomplete">
  <ul id="autocomplete-results">
    <li class="auto-li">blue</li>
  </ul>
</div>

and want to add a class to the first auto-li when the user keys down.

I have the following javascript:

document.onkeydown = checkKey;
 function checkKey(e){
 e = e || window.event;

 if(e.keyCode=='40')
 {
   $('#autocomplete-results li:nth-child(0)').text('not working');
   console.log('here is 40'); //code
 }
}

But it's not working - what do I need to change?

thx in advance

Upvotes: 4

Views: 3173

Answers (3)

Musa
Musa

Reputation: 97727

The :nth-child pseudo-class starts at index 1 not 0

The nth child pseudo-class won't actually help in selecting the first .auto-li, you can use :first, .eq(0) or :eq(0) to filter the selection to just the first .auto-li

$('#autocomplete-results li.auto-li').eq(0).text('working');

Upvotes: 6

elrado
elrado

Reputation: 5292

document.onkeydown = checkKey;
 function checkKey(e){
 e = e || window.event;



 if(e.keyCode===40)
 {    
     $('#autocomplete-results li:nth-child(1)').text('not working');
   alert('here is 40'); //code
 }
}

Nth-child index starts with index 1 and not with standard list index 0.

And do not do the comparison with =='40' buth with === 40, so there is no unnecesery type conversion (buth that has nothing to do with correctnes of you're code).

Upvotes: 1

user1726343
user1726343

Reputation:

If you want to select the first auto-li, your selector should actually be:

$('#autocomplete-results li.auto-li:first')

Upvotes: 2

Related Questions