jQuery Create a Custom Filter That Finds Elements With Data


/ Published in: jQuery
Save to your folder(s)

This is dead handy. The purpose of the custom filter is to select all elements which have data attached. You can even find specific data.


Copy this code and paste it in your HTML
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5.  
  6. <script type="text/javascript" src="../assets/js/jquery.js"></script>
  7. <script type="text/javascript">
  8.  
  9. $(function() {
  10.  
  11. jQuery.expr[':'].data = function(elem, index, m) {
  12. // Remove ":data(" and the trailing ")" from the match, as these parts aren't needed:
  13. m[0] = m[0].replace(/:data\(|\)$/g, '');
  14. var regex = new RegExp('([\'"]?)((?:\\\\\\1|.)+?)\\1(,|$)', 'g'),
  15. // Retrieve data key:
  16. key = regex.exec( m[0] )[2],
  17. // Retrieve data value to test against:
  18. val = regex.exec( m[0] );
  19. if (val) {
  20. val = val[2];
  21. }
  22. // If a value was passed then we test for it, otherwise we test that the value evaluates to true:
  23. return val ? jQuery(elem).data(key) == val : !!jQuery(elem).data(key);
  24. };
  25.  
  26.  
  27. $("#aa").data("id",123);
  28. $("#ab").data("id",245);
  29. $("#ac").data("id",678);
  30.  
  31. //find all that have id
  32. $("p:data('id')").css("color","blue");
  33. //find all that have an id of 123
  34. $("p:data('id',123)").css("color","red");
  35.  
  36. });
  37.  
  38. </script>
  39. </head>
  40. <body>
  41. <div id="wrapper">
  42. <em>Example!</em>
  43. <p id="aa">sdf sadf dsf fds</p>
  44. <p id="ab">sdf sadf dsf fds</p>
  45. <p id="ac">sdf sadf dsf fds</p>
  46. <p id="ad">sdf sadf dsf fds</p>
  47. </div>
  48. </body>
  49. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.