How to Filter Objects by Data Attribute Value in jQuery ?
In this article, we will learn how to filter objects by their data attribute value in jQuery. There are two approaches that can be taken to achieve this:
Approach 1: Using the this property and filter(), data() and css() methods in the jQuery library. There are four division elements that are defined in the following example, each having some data attribute with its corresponding value. We apply the filter() method to each division element which takes an anonymous function as its parameter. This anonymous function returns either the boolean true or false, depending on whether the value of the data attribute of each division element is equal to a particular string ( string is “valid”). To check this, the data() method is used which takes the attribute name after the data- prefix as a string parameter.
After this, we chain the css() method with the filter() method to apply some styling on all the filtered elements or objects based on the functionality discussed above.
Example: In the following example, the data-attribute has been named as data-geek and all the filtered elements have been styled with a font color of green.
Approach 2: Using the filter() and css() methods in the jQuery library. This approach is quite similar to the previous approach but the syntax is slightly cleaner and condensed. We are checking if the value of the data attribute of each division element is equal to the string “open” instead of the string “valid” to filter the division elements.
Example: In the following example, the data-attribute has been named as data-state and all the filtered elements have been styled with a font colour of teal.