jQuery .end() and 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 () { $('div') .find('p').css("background", "yellow") .end() .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.
Feel free to contact me for any help related to jQuery, I will gladly help you.