This short code snippet makes it possible to carry out multiple operations on the children of any particular parent (within the DOM) while retaining the original subject of the chain:

The Code:

// $.fn.with:
// Used to process child nodes while
// retaining parent within chain.
 
$.fn.with = function(elems,action){ 
    return this.each(function(){
        $(elems,this).each(action);
    });
}

Note: As dave pointed out in the comments, with is a reserved word in JavaScript so technically shouldn’t be used as an identifier. If you’re going to use this code then it’s probably best if you change the name of it from ‘with’ to ‘withChildren’ or anything else.

Explanation:

It’s hard to explain exactly what you’d use this for, so I’ll show you instead:

Using jQuery’s native methods, you have to continually traverse the DOM to find elements, and doing this continually changes the subject of the chain. For example:

$('#elem')
    .hide()
    .find('a').each(function(){
        $(this).width( $(this).width+200 );
    })
    .end() // Traverse back to #elem
    .find('em').each(function(){
        $(this).width( $(this).width+100 );
    })
    .end() // Traverse back to #elem
    .fadeIn()

As you can see, in order to re-select the parent ($('#elem')) we have to keep on using the end() method. This may seem intuitive to you but it can result in unnecessarily bloated code! Additionally, instead of only traversing the DOM you’re forced to traverse the chain as well; this makes keeping track of things all the more tricky!

Usage:

So, using this new ‘with’ method you might achieve the above functionality like this:

$('#elem')
    .hide()
    .with('a',function(){
        $(this).width( $(this).width+200 );
    })
    .with('em',function(){
        $(this).width( $(this).width+100 );   
    })
    .fadeIn()

Easy!

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!