Home >Web Front-end >JS Tutorial >Detailed explanation of the has() method based on jquery and the difference between it and the find() method and filter() method_jquery
has(selector or DOM element) Set the set of matching elements based on the selector or DOM element as a condition, retrieve whether the condition exists in the descendants of each element, and form a new result set with elements that meet the condition.
The following is an example:
As can be seen from this example: when matching li, check whether the descendant elements of the li contain span. If so, the element is included in the result. If not included, then excluded.
Note: has only serves as a judgment. Use the selector or DOM element in the has parameter as a condition to check whether the elements in the original result set match. Remove the non-matching elements and form a new result set with the matching elements.
This is different from the find() method, which obtains the descendants of each element in the current result set. Parameters (selectors, jquery collections or DOM elements) are used as filter conditions. Those that meet the filter conditions are retained, and those retained are descendants. In the has() method, the parameters are only used as conditions. If the conditions are met, its previous elements will be added to the new result set, rather than the descendants.
$('li').find('span').css('background-color', 'red');The result is:
The parameters in the filter() method and has() method are all filtering conditions. The difference is that in the filter() method, the condition is applied to itself; in the has() method, the condition is applied to its descendant elements.
li, and the has() method condition is applied to li Descendant elements
< /li>