Finding Immediately Adjacent Siblings
Greetings! Here’s a quick tip for advanced filtering of adjacent sibling nodes.
Given the following HTML:
1 2 3 4 5 6 7 8 | <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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | /* * immediateSiblings 1.1.0 (2009-10-19) * * Copyright (c) 2006-2009 Jonathan Sharp (http://jdsharp.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://jdsharp.com/ * * Built upon jQuery 1.3.2 (http://jquery.com) */ $.fn.immediateSiblings = function(selector) { var siblings = []; this.each(function() { var children = $(this).parent().children(selector).not(this).get(); $.merge(siblings, children); }); return this.pushStack( $.unique( siblings ) ); }; |
Cheers,
-Jonathan