jQuery.hasData()

jQuery

jQuery.hasData()


jQuery.hasData( element ) Returns: Boolean

Description: Determine whether an element has any jQuery data associated with it.

  • version added: 1.5jQuery.hasData( element )

    • element
      Type: Element
      A DOM element to be checked for data.

The jQuery.hasData() method provides a way to determine if an element currently has any values that were set using jQuery.data(). If no data is associated with an element (there is no data object at all or the data object is empty), the method returns false; otherwise it returns true.

The primary advantage of jQuery.hasData(element) is that it does not create and associate a data object with the element if none currently exists. In contrast, jQuery.data(element) always returns a data object to the caller, creating one if no data object previously existed.

Note that jQuery's event system uses the jQuery data API to store event handlers. Therefore, binding an event to an element using .on(), .bind(), .live(), .delegate(), or one of the shorthand event methods also associates a data object with that element.

Example:

Set data on an element and see the results of hasData.

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
                                  
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Results: </p>
<script>
var $p = jQuery("p"), p = $p[0];
$p.append(jQuery.hasData(p)+" "); /* false */
$.data(p, "testing", 123);
$p.append(jQuery.hasData(p)+" "); /* true*/
$.removeData(p, "testing");
$p.append(jQuery.hasData(p)+" "); /* false */
$p.on('click', function() {});
$p.append(jQuery.hasData(p)+" "); /* true */
$p.off('click');
$p.append(jQuery.hasData(p)+" "); /* false */
</script>
</body>
</html>