Return to Snippet

Revision: 32143
at September 19, 2010 13:13 by Meander365

Initial Code
<!DOCTYPE html>
<html xmlns="">
<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);

	//find all that have id
	//find all that have an id of 123

	<div id="wrapper">
		<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>

Initial URL

Initial Description
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.

Initial Title
jQuery Create a Custom Filter That Finds Elements With Data

Initial Tags
data, jquery, filter

Initial Language