Filtering a Wrapper Set of DOM Elements - J Query

Problem
You have a set of selected DOM elements in a jQuery wrapper set but want to remove DOM elements from the set that do not match a new specified expression(s) in order to create a new set of elements to operate on.

Solution

The jQuery filter method, used on a jQuery wrapper set of DOM elements, can exclude elements that do not match a specified expression(s). In short, the filter() method allows you to filter the current set of elements. This is an important distinction from the jQuery find method, which will reduce a wrapped set of DOM elements by finding (via a new selector expression) new elements, including child elements of the current wrapped set.
To understand the filter method, let’s examine the following code:

The HTML page in the code example just shown contains a web page with 10 <a> elements. Those links that are external links are given a class name of external. Using the jQuery function, we select all <a>elements on the page. Then, using the filter method, all those elements that do not have a class attribute value of external are removed from the original set. Once the initial set of DOM elements are altered using the filter() method, I invoke the length property, which will tell me how many elements are now in my new set after the filter has been applied.

Discussion

It’s also possible to send the filter() method a function that can be used to filter the wrapped set. Our previous code example, which passes the filter() method a string expression, can be changed to use a function instead:

Notice that I am now passing the filter() method an anonymous function. This function is called with a context equal to the current element. That means when I use $(this) within the function, I am actually referring to each DOM element in the wrapper set. Within the function, I am checking each <a>element in the wrapper set to see whether the element has a class value (hasClass()) of external. If it does, Boolean true, then keep the element in the set, and if it doesn’t (false), then remove the element from the set. Another way to look at this is if the function returns false, then the element is removed. If the function returns any other data value besides false, then the element will remain in the wrapper set.
You may have noticed that I have passed the function a parameter named index that I am not using. This parameter, if needed, can be used to refer numerically to the index of the element in the jQuery wrapper set.


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

J Query Topics