jQuery .end() and Chaining

Before you go further, I assume that you know What is chaining in context of jQuery? If not, then first read "What is Chaining in jQuery?". To summarize Chaining in jQuery means to connect multiple functions, events on selectors. Main advantage of using chaining is that it makes code look clean and gives better performance. You should make a habit of using chaining.

Related Post:

You will find that chaining is very easy to implement and indeed it is. But consider a scenario, where in a <div> element, find all <p> and <span> elements and assign background color to them. Below jQuery code will exactly do the needful.

$(document).ready(function () {
   $('div').find('p').css("background", "yellow");
   $('div').find('span').css("background", "pink");

Can this be done using chaining? The first line of code $('div').find('p'), will select all the <p> tag element in <div> and change background color. Since using find() we have filtered out all <p> elements so we need to use selector again to select <span>tag element and we can't use chaining. Fortunately, jQuery has .end() function which end the most recent filtering operation in the current chain and return to its previous state. Like,

$(document).ready(function () {
       .find('p').css("background", "yellow")
       .find('span').css("background", "pink");

This chain searches for <p> tag element in <div> and turns their backgrounds yellow. Then .end() returns the object to its previous state which was before the call to find(), so the second find() looks for <span> inside <div>, not inside <p>, and turns the matching elements' backgrounds to pink. The .end() method is useful primarily when exploiting jQuery's chaining properties.

See Complete Code

Feel free to contact me for any help related to jQuery, I will gladly help you.