What's the best way to filter and find from a jQuery object?
HTML
<div class="box"></div>
<div class="box"></div>
<section>
<div class="box"></div>
</section>
CSS
section { display: block }
.box {
width: 100px;
height: 20px;
background: blue;
margin-bottom: 1px;
}
JavaScript
// I know I could just select $('.box'), but let's say that I'm using selection in a method. The user passes in a jQuery object.
var $children = $( document.body ).children();
// What's the best way to filter and find from a jQuery object?
var $boxes = $children
.filter('.box')
.add( $children.find('.box') );
// $boxes.css( 'backgroundColor', 'red' );
// so...
// andSelf() can usually help in instances like this
// but it looks like you cant get from one .box selection to the others in a single jump.
// it always requires two traversal method calls.
// it'd be fun if this worked...
var $boxes = $children
.filter('.box').siblings()
.find('.box').andSelf().andSelf()
.filter('.box');
// and i think it might have in a previous jQuery version when the pushStack shit was handled differently. but alas.. it doesnt
// and there is no .andLastSelf() that would pick the object from two selections back.
// and hacking that in isnt at all easy
// then i tried something like
$children.filter('.box').find(' ~ .box')
// but that doesnt work because find only looks inside and not amongst.
// which is a mega-bummer because the siblings selector is so sexy and hispanic. ;)
// olé!
// and so. yet another boring ass jquery plugin.
$.fn.filterAndFind = function(sel){ return this.filter(sel).add( this.find(sel) ); }
$children.filterAndFind('.box').css( 'backgroundColor', 'red' );