:data() Selector


data selector

Description: Selects elements which have data stored under the specified key.

  • jQuery( ":data(key)" )

    key: The data key.

The expression $( "div:data(foo)") matches a <div> if it has data stored via .data( "foo", value ).

Example:

Select elements with data and change their background color.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>data demo</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<style>
div {
width: 100px;
height: 100px;
border: 1px solid #000;
float: left;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<script>
$( "#one" ).data( "color", "blue" );
$( "#three" ).data( "color", "green" );
$( ":data(color)" ).each(function() {
var element = $( this );
element.css( "backgroundColor", element.data( "color" ) );
});
</script>
</body>
</html>

Demo: