jQuery.hasData()

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

jQuery.hasData(element)🡢 Boolean

element ElementA 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 there is no data object associated with an element, 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.

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

JS
<p>Results:</p>
HTML
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
DEMO

Looking for a Web Developer?

👋

Hi! I'm Basti, author of this site. If you are looking for a web developer with 15+ years of experience, holla at me!

Be it the good 'ol jQuery, vanilla JS or modern frameworks like Vue and Svelte, front- or backend, I can help you.

Just write me at jobs@jqapi.com :)