jQuery.hasData()
Categories: Data
jQuery.hasData( element )Returns: Boolean
Description: Determine whether an element has any jQuery data associated with it.
-
jQuery.hasData( element )
version added: 1.0element 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.
-
Set data on an element and see the results of hasData.
HTML:
<p>Results: </p>
Code:
$(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 */ });