Categories
jQuery

jQuery Chaining

jQuery is the jewel in the crown that is web development. Once you discover it, Javascript is no longer a chore to write, hell, it might even be considered fun! Sure being able to select elements by ID, class, or type is great, but what about all the other stuff? What about chaining? I’ve heard such great stuff about it!

Chaining

The first thing you need to know about chaining is that you chain actions on to collections. A collection is what is returned when you select something using jQuery.

$("input");  //Collection of all input elements on the page.

When most people start using jQuery, they do something like this:

$("input").val("123");
$("input").addClass("awesome");
$("input").attr("data-bind", "15");

Yes, this code will work, but it’s inefficient. Every time you perform a selection, jQuery must traverse the DOM and find all the input elements. If you use chaining, it will simply use the collection of input elements that it already has.

$("input")
	.val("123")
	.addClass("awesome")
	.attr("data-bind", "15");

So why does this work? Because each method that you call in the chain returns the collection. So in this case “val()”, “addClass()”, and “attr()” all return “$(input)”. However, not all methods support chaining. For instance, the “text()” method breaks the chain, so if you’re going to use it, do it at the end.
What if you want to keep the chain alive though? No problem. You can simply back-out of the destructive action using the “end()” method.

Before

<ol id='mylist'>
	<li>
	</li>
	<li>
	</li>
	<li>
	</li>
</ol>

Javascript

$('#mylist')
	.find('>li')
		.filter(':last')
			.addClass('Meow')
		.end()
		.filter(':first')
			.addClass('Mix')
		.end()
		.addClass('catfood')
	.end()
	.addClass('thelist');

After

<ol id='mylist' class='thelist'>
	<li class='Mix catfood'>
	</li>
	<li class='catfood'>
	</li>
	<li class='Meow catfood'>
	</li>
</ol>

While sometimes confusing, you can see that chaining is often the most efficient way to handle modifying the DOM.

Writing Chainable Plugins/Functions

Now that you know all about chaining, you’ll probably want to write your own chainable plugins/functions. It’s very easy to do this, since all you need to do is return the jQuery object at the end of the function.

In this example, we’ll write a plugin that attaches a second counter to an element.

Plugin

(function($) {
	$.fn.count = function() {
		return this.each(function() {  //We do an 'each', because the collection may have more than one item in it.
			var self = $(this);  //
			self.html('0');
			var theInterval = window.setInterval(function() {
				var c = parseFloat(self.text());
				self.html(c + 1);
			}, 1000);
		});
	}
}) (jQuery);

HTML

<div>
	<span id='test'></span>
</div>

Execution

$("#test").count().parent().addClass('counters'); //Chaining still works :)