How do you use jQuery's filter() method to selectively manipulate a subset of DOM elements?
How do you use jQuery's filter() method to selectively manipulate a subset of DOM elements?
276
09-May-2023
Updated on 11-May-2023
Aryan Kumar
10-May-2023To use jQuery's filter() method to selectively manipulate a subset of DOM elements, you can follow these steps:
Here's an example code snippet to demonstrate the above steps:
In this example, we start by selecting all the li elements with class "fruit" and filtering the ones that contain the letter "a" using a function that checks the text content. We then change the CSS color of the filtered fruits using the css() method.
Next, we select all the li elements with class "vegetable" and filter the ones that are not the first child using a filter() method with the :not() and :first-child selectors. We then add a class to the filtered vegetables using the addClass() method.
The result is that the filtered fruits are highlighted in red, and the filtered vegetables are highlighted with a custom class. By using the filter() method, we can selectively manipulate only the elements that meet certain criteria, without affecting the rest of the DOM elements.