Adjacent

Click on one of the words below to highlight all the adjacent elements of type "foo".

Foo

Bar

Foo

Foo

Foo

Foo

Bar

Foo

Foo

Foo

Bar

Foo

Foo

Foo

$.fn.adjacent = function(filter) {
  var $all = this;

  for (var $curr = this.prev(filter);
       $curr.length > 0;
       $curr = $curr.prev(filter)) {
    $all = $all.add($curr);
  }
  for (var $curr = this.next(filter);
       $curr.length > 0;
       $curr = $curr.next(filter)) {
    $all = $all.add($curr);
  }
  return $all;
};

$('p.foo,p.bar').click(function() {
  $(".selected").removeClass("selected");

  $(this)
    .adjacent('.foo')
    .addClass('selected')
  ;
});

Download at: http://plugins.jquery.com/project/Adjacent