mikelbring
mikelbring

Reputation: 1492

Get the next element by selecting element with a class

I have a live search and a list element is given a class of hover I am then trying to get the next li element after the hover class upon pressing the down arrow and adding the hover class to that element. Here is what I have:

    if(e.keyCode == 40){
        var current = results.find('li.hover');
        current.removeClass();
        current.parent().next('li').addClass('hover');
        return false;
    }

It just will not add a class to the next element. It finds the current class just fine. Not sure what I am doing wrong. Appreciate it!

Upvotes: 0

Views: 657

Answers (5)

COBOLdinosaur
COBOLdinosaur

Reputation: 294

current.nextSibling should refer to the next li element in the list

Upvotes: 0

fflorent
fflorent

Reputation: 1646

Do not you just want to do that :

if(e.keyCode == 40){
    var current = results.find('li.hover');
    current.removeClass();
    current.next('li').addClass('hover');
    return false;
}

without parent() ?

Upvotes: 0

jfriend00
jfriend00

Reputation: 707328

current.parent().next('li') is probably not doing what you want.

Since current is a jQuery object of li tags, I assume that it's parent is a ul tag. If that's the case, then next('li') is looking for a first sibling of the ul tag that's an li tag which it will never find.

It's unclear to me which li you want to add the hover class to so I'm not sure exactly what to recommend to do what you want.

Upvotes: 0

Blender
Blender

Reputation: 298176

Use e.which, not e.keyCode. jQuery normalizes the property (IE doesn't support e.keyCode):

if(e.which == 40){

As for your selector, try this:

results.find('li.hover').removeClass().next('li').addClass('hover')

.next() looks for the next sibling matching the selector, so there is no need to call .parent().

Upvotes: 3

Niels
Niels

Reputation: 49919

You are looking for the LI.hover, after that you go to the parent (which is the UL) and then select the next LI after the UL.

Change this:

current.parent().next('li').addClass('hover');

To:

current.next('li').addClass('hover');

Upvotes: 2

Related Questions