jQuery Traversal - end() Method
Example
Select all paragraphs, find the span elements within these paragraphs, and then restore them to paragraphs, setting the paragraphs to have a two-pixel red border:
$("p").find("span").end().css("border", "2px red solid");
Definition and usage
The end() method ends the most recent filter operation in the current chain and restores the matching element set to its previous state.
Syntax
.end()
Detailed explanation
Most jQuery traversal methods operate on a jQuery object instance and generate a new object that matches a set of different DOM elements. When this happens, the new element set should be pushed into the stack maintained in the object. Each successful filter method call will push the new element into the stack. If we need the old element set, we can use end() to pop the new collection from the stack.
Assuming there are a pair of short lists on the page:
<ul class="first"> <li class="foo">list item 1</li> <li>list item 2</li> <li class="bar">list item 3</li> </ul> <ul class="second"> <li class="foo">list item 1</li> <li>list item 2</li> <li class="bar">list item 3</li> </ul>
Example 1
jQuery is particularly useful when using the chaining property (command chain). Without using the command chain, we usually call the previous object by variable name, so we do not need to manipulate the stack. However, through end(), we can chain all method calls together:
$('ul.first').find('.foo').css('background-color', 'red') .end().find('.bar').css('background-color', 'green');
This command chain retrieves the items with the class name foo from the first list and sets their background to red. The end() function restores the object to the state before the find() call, so the second find() looks for '.bar' within <ul class="first">, not within the <li class="foo">, and sets the background color of the matched elements to green. The final result is that items 1 and 3 in the first list have colored backgrounds, while there are no changes to the items in the second list.
Example 2
This long jQuery chain can be visualized as a structured code block, where the nesting code block is opened by the filter method, and the end() method is used to close the code block:
$('ul.first').find('.foo') .css('background-color', 'red') .end().find('.bar') .css('background-color', 'green') .end();
The end() function is not necessary because we will discard this jQuery object later. However, if you write the code in this form, end() can provide visual symmetry and a neat program feel, at least making it easier for developers to read. Of course, the cost is a little performance loss due to the additional call.