Greetings! Here’s a quick tip for advanced filtering of adjacent sibling nodes.

Given the following HTML:

<ul>
<li>Item 1</li>
<li class=”hello”>Item 2</li>
<li class=”hello” id=”three”>Item 3</li>
<li class=”hello”>Item 4</li>
<li>Item 5</li>
<li class=”hello”>Item 6</li>
</ul>

If you needed to select the immediate siblings of #three that matched the class .hello (so the resulting element set would be Item 2, Item 3, Item 4) there isn’t an easy way to do this. jQuery provides a prev() and prevAll() methods (as well as their next() counter parts) but that would return all of the elements. Here’s a jQuery immediateSiblings function to take care of this for us:

$(’#three’).immediateSiblings(’li.hello’)

Here’s the code for the plugin:

/*
* immediateSiblings 1.0.0 (2008-07-14)
*
* Copyright (c) 2006,2007 Jonathan Sharp (http://jdsharp.us)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://jdsharp.us/
*
* Built upon jQuery 1.2.6 (http://jquery.com)
*/
$.fn.immediateSiblings = function(selector) {
var siblings = [];
if ( this.length > 0 ) {
this.each(function() {
var elm = $(this);
while ( elm.prev().is( selector ) ) {
elm = elm.prev();
siblings.unshift( elm[0] );
}
siblings.push( this );
var elm = $(this);
while ( elm.next().is( selector ) ) {
elm = elm.next();
siblings.push( elm[0] );
}
});
}
return this.pushStack( $.unique( siblings ) );
};

Cheers,
-Jonathan