Finding Descendant Elements Within the Currently Selected Wrapper Set - J Query

Problem

You have a set of selected DOM elements (or a single element) and want to find descendant(children) elements within the context of the currently selected elements.

Solution

Use the .find() method to create a new wrapper set of elements based on the context of the current set and their descendants. For example, say that you have a web page that contains several paragraphs. Encapsulated inside of these paragraphs are words that are emphasized (italic). If you’d like to select only <em>elements contained within <p>elements, you could do so like this:

Keep in mind that we could have also written this code by passing a contextual reference as a second parameter to the jQuery function:

Additionally, it’s worth mentioning that the last two code examples are demonstrative in purpose. It is likely more logical, if not pragmatic, to use a CSS selector expression to select all the descendant italic elements contained within the ancestor <p>elements.

Discussion

The jQuery.find() method can be used to create a new set of elements based on context of the current set of DOM elements and their children elements. People often confuse the use of the .filter() method and .find() method. The easiest way to remember the difference is to keep in mind that .find() will operate/select the children of the current set while .filter() will only operate on the current set of elements. In other words, if you want to change the current wrapper set by using it as a context to further select the children of the elements selected, use .find(). If you only want to filter the current wrapped set and get a new subset of the current DOM elements in the set only, use .filter(). To boil this down even more, find() returns children elements, while filter() only filters what is in the current wrapper set.


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

J Query Topics