jQuery Data - hasData() Method
Example
Set data on the element and then view the result of hasData:
$(function(){ var $p = jQuery("p"), p = $p[0]; $p.append("jQuery.hasData(p)+" "); /* false */ jQuery.data(p, "testing", 123); $p.append("jQuery.hasData(p)+" "); /* true */ jQuery.removeData(p, "testing"); $p.append("jQuery.hasData(p)+" "); /* false */ });
Definition and Usage
The hasData() method checks if the element has any jQuery data associated with it.
Syntax
jQuery.hasData("element)
Parameters | Description |
---|---|
element | Optional. The DOM element whose data needs to be checked. |
Detailed Description
The jQuery.hasData() method checks if the element currently has any values set through jQuery.data(). If no data is associated with the element (the data object does not exist or is empty), this method returns false; otherwise, it returns true.
jQuery.hasData("elementThe main advantage of which is that it will not create a data object and associate it with the element if there is no data object. Instead, jQuery.data("elementAlways returns a data object to the caller; if a data object does not exist, it will create it.