/ Published in: jQuery
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="../assets/js/jquery.js"></script> <script type="text/javascript"> $(function() { jQuery.expr[':'].data = function(elem, index, m) { // Remove ":data(" and the trailing ")" from the match, as these parts aren't needed: m[0] = m[0].replace(/:data\(|\)$/g, ''); var regex = new RegExp('([\'"]?)((?:\\\\\\1|.)+?)\\1(,|$)', 'g'), // Retrieve data key: key = regex.exec( m[0] )[2], // Retrieve data value to test against: val = regex.exec( m[0] ); if (val) { val = val[2]; } // If a value was passed then we test for it, otherwise we test that the value evaluates to true: return val ? jQuery(elem).data(key) == val : !!jQuery(elem).data(key); }; $("#aa").data("id",123); $("#ab").data("id",245); $("#ac").data("id",678); //find all that have id $("p:data('id')").css("color","blue"); //find all that have an id of 123 $("p:data('id',123)").css("color","red"); }); </script> </head> <body> <div id="wrapper"> <em>Example!</em> <p id="aa">sdf sadf dsf fds</p> <p id="ab">sdf sadf dsf fds</p> <p id="ac">sdf sadf dsf fds</p> <p id="ad">sdf sadf dsf fds</p> </div> </body> </html>