Chain jQuery methods


Problem

When you want to change lots of things about a single element you end up having to write a lot of code if you don't know about chaining. Here's an example where we are changing a few things:

$('#element-id').removeClass('hidden');
$('#element-id').css('color', 'red');
$('#element-id').text('Now red and visible');

How can we write this with less code?



Solution

The first idea might be a variable which is certainly a good idea as we don't have to duplicate the ID of our element. That would make a later change easier:

var $element = $('#element-id');
$element.removeClass('hidden');
$element.css('color', 'red');
$element.text('Now red and visible');

However, jQuery offers and even shorter syntax, something that is called chaining:

$('#element-id').removeClass('hidden').css('color', 'red').text('Now red and visible');

Please note that it's also fine to wrap this on multiple lines:

$('#element-id')
   .removeClass('hidden')
   .css('color', 'red')
   .text('Now red and visible');

This is achieved by returning the object itself in each of these methods. That's a so called fluent interface. More about how it's implemented in JavaScript and other languages can be found here: https://en.wikipedia.org/wiki/Fluent_interface

Comments




Please sign-in to post a comment