Returning to the Prior Selection Before a Destructive Change - J Query

A destructive jQuery method (e.g., filter() or find()) that was used on a set of elements needs to be removed so that the set prior to the use of the destructive method is returned to its previous state and can then be operated as if the destructive method had never been invoked.


jQuery provides the end() method so that you can return to the previous set of DOM elements that were selected before using a destructive method. To understand the end() method, let’s examine the following HTML.

The first alert() statement in the code contains a jQuery statement that will search the document for all <p>elements and then apply filter() to the selected <p>elements in the set selecting only the one(s) with a class of middle. The length property then reports how many elements are left in the set:

The next alert() statement makes use of the end() method. Here we are doing everything we did in the prior statement except that we are undoing the filter() method and returning to the set of elements contained in the wrapper set before the filter()method was applied:

The last alert() statement demonstrates how the end() method is used twice to remove both the filter() and find() destructive changes, returning the wrapper set to its original composition:

If the end() method is used and there were no prior destructive operations performed, an empty set is returned. A destructive operation is any operation that changes the set of matched jQuery elements, which means any traversing or manipulation method that returns a jQuery object, including add(), andSelf(), children(), closes(), filter(), find(), map(), next(), next All(), not(), parent(), parents(), prev(), prevAll(), siblings(), slice(), clone(), append To(), prependTo(), insert Before(), insertAfter(), and replaceAll().

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics