There is no built-in method for this, but it is easy to do without using if / else :
$(document).on("click", "#footer button", function () { var that = $(this), index = that.index(), prev = that.prevAll('button:lt(4)'), next = that.nextAll('button:lt(4)'); that.siblings().removeClass('highlight'); that.add(prev).add(next).addClass('highlight'); });
JS Fiddle demo .
By the way, a simple plugin could be easily created / used:
(function($){ $.fn.rangedHighlight = function(range,highlight) { var that = this, prev = that.prevAll().slice(0,range), next = that.nextAll().slice(0,range); that.siblings().addBack().removeClass(highlight); that.add(prev).add(next).addClass(highlight); return this; }; })(jQuery); $('#footer').on('click', 'button', function(){ $(this).rangedHighlight(4,'highlight'); });
JS Fiddle demo .
Unfortunately, I did not notice, until the comments indicated the need to always select the full specified range of elements, even if this offsets the element that clicked in the center from the selected section. There seems to be no way to do this without using if / else some kind (although I'm trying to simplify it).
While the above remains true (there is no built-in method), I decided to rewrite the plugin to offer a choice for this (if used for you):
(function($){ $.fn.rangedHighlight = function(opts) { var that = this, index = that.index(), s = $.extend({ 'range' : 9, 'highlight' : 'highlight', 'highlightClicked' : false, 'alwaysShowFull' : true, 'returnRange' : false }, opts), eitherSide = Math.floor(s.range - 1)/2, all = that.parent().children(), leftLimited = index < eitherSide, rightLimited = index > all.length - eitherSide - 1, rangeMin, rangeMax, returnObject; that.addClass(s.highlightClicked, 'string' === typeof s.highlightClicked); if (!leftLimited && !rightLimited) { rangeMin = index - eitherSide; rangeMax = index + eitherSide + 1; } else if (s.alwaysShowFull && (leftLimited || rightLimited)) { rangeMin = leftLimited ? 0 : all.length - s.range; rangeMax = leftLimited ? s.range : all.length; } else if (!s.alwaysShowFull && (leftLimited || rightLimited)) { rangeMin = leftLimited ? 0 : index - eitherSide; rangeMax = leftLimited ? index + eitherSide + 1 : all.length; } that.siblings('.' + s.highlight).removeClass(s.highlight); all.slice(rangeMin, rangeMax).addClass(s.highlight); returnObject = s.returnRange === false ? this : all.slice(rangeMin,rangeMax); return returnObject; }; })(jQuery); $('#footer').on('click', 'button', function(){ $(this).rangedHighlight({
JS Fiddle demo .
Literature: