Search code examples
javascriptjqueryjquery-selectors

Select next element via class with jQuery one at a time


Backstory: I have HTML that's been searched for a phrase, which puts a span around each instance. So if I search for Lorem, every place that word appears, it will look like this:

<span class="live-search-highlight">Lorem</span>

Which gives it a little highlight.The very first instace is given a different class with a more distinct highlight like this:

<span class="highlight-current">Lorem</span>

Question: I want to click a button, and starting at .highlight-current, I want to find the next instance of .live-search-highlight and switch its class to .highlight-current. How can I achieve this with jQuery? Here is what I have so far, which only works once:

$(document.body).on('click','.button', function(){

    // Find highlight-current, then get the next instance and make that one current

    $('.highlight-current').parent().nextAll(".live-search-highlight").eq(0).removeClass('live-search-highlight').addClass('highlight-current');

    // Reset the previous one so it's no longer current

    $('.highlight-current:first').removeClass('highlight-current').addClass('live-search-highlight');

});

JsFiddle: http://jsfiddle.net/kthornbloom/g5skaek7/3/


Solution

  • Simpler to just create a collection of all of the highlighted elements. Then use indexing to determine position of current/next.

    Following will revert back to the start when the last one is reached

    // create collection of all highlighted elements
    var $highlights = $('.live-search-highlight'),
        // isolate the current one from collection and remove the secondary class
        $currHighlight = $highlights.filter('.highlight-current').removeClass('highlight-current'),
        // use index of current to determine next
        nextIndex = $highlights.index($currHighlight) + 1;
    // revert to beginning if index is at the end
    if(nextIndex === $highlights.length){
        nextIndex = 0;
    }
    // add secondary class to next (or first) in collection
    $highlights.eq(nextIndex).addClass('highlight-current');
    

    I would leave the main class and only add/remove the secondary class

    DEMO