javascript - Select next element via class with jQuery one at a time -


backstory: have html that's been searched phrase, puts span around each instance. if search lorem, every place word appears, this:

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

which gives little highlight.the first instace given different class more distinct highlight this:

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

question: want click button, , starting @ .highlight-current, want find next instance of .live-search-highlight , switch class .highlight-current. how can achieve jquery? here have far, works once:

$(document.body).on('click','.button', function(){      // find highlight-current, next instance , make 1 current      $('.highlight-current').parent().nextall(".live-search-highlight").eq(0).removeclass('live-search-highlight').addclass('highlight-current');      // reset previous 1 it's no longer current      $('.highlight-current:first').removeclass('highlight-current').addclass('live-search-highlight');  }); 

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

simpler create collection of of highlighted elements. use indexing determine position of current/next.

following revert start when last 1 reached

// create collection of highlighted elements var $highlights = $('.live-search-highlight'),     // isolate current 1 collection , remove secondary class     $currhighlight = $highlights.filter('.highlight-current').removeclass('highlight-current'),     // use index of current determine next     nextindex = $highlights.index($currhighlight) + 1; // revert beginning if index @ end if(nextindex === $highlights.length){     nextindex = 0; } // add secondary class next (or first) in collection $highlights.eq(nextindex).addclass('highlight-current'); 

i leave main class , add/remove secondary class

demo


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -