Jquery next () and elements that are not necessarily next to each other

I know there are other questions on this, but I was not able to get anyone to work, so I will ask again:

I have an html list that looks like this:

<ul> <li>Item one</li> <li>Item two</li> <li>Item three</li> <li>Item four</li> <li>Item five</li> </ul> 

Using jQuery, some of the li tags are hidden, and some are visible with .show () and .hide (), for example.

 <ul> <li style="display: block">Item one</li> <li style="display: none">Item two</li> <li style="display: none">Item three</li> <li style="display: block">Item four</li> <li style="display: block">Item five</li> </ul> 

I also have another jQuery bit that adds a class to one of the li tags, so the code looks like this (the code will only ever add this class to visible li):

 <ul> <li style="display: block" class="highlight">Item one</li> <li style="display: none">Item two</li> <li style="display: none">Item three</li> <li style="display: block">Item four</li> <li style="display: block">Item five</li> </ul> 

What I then need to do is when the event occurs (in this case, the user presses the down key). I want li with the class to delete its class and add the class to the next visible one. I would think that would do this:

 if (event.keyCode == '40') { $('li.highlight').removeClass('highlight').next(':visible').addClass('highlight'); } 

But this only works if the next visible li is the next li. How can I make him choose the right item in all cases?

+4
source share
1 answer

Try:

 $('li.highlight') .removeClass('highlight') .nextAll(':visible:first') .addClass('highlight'); 

Annoyingly, and vaguely, the next will only choose the next brother. The fact that you can filter by going to the selector makes you think that it will continue until it finds something, but it is not. Expressing the filter will cause next to capture the very next element only if it matches the passed selector.

See http://api.jquery.com/nextAll/

+10
source

Source: https://habr.com/ru/post/1316306/


All Articles