Is there a way that I can check if a data attribute exists?

Is there a way that I can check if a data attribute exists?

Is there some way that I can run the following:
var data = $(“#dataTable”).data(‘timer’);
var diffs = [];

for(var i = 0; i + 1 < data.length; i++) { diffs[i] = data[i + 1] - data[i]; } alert(diffs.join(', ')); Only if there is an attribute called data-timer on the element with an id of #dataTable?


Solution 1:

if ($("#dataTable").data('timer')) {

NOTE this only returns true if the data attribute is not empty string or a “falsey” value e.g. or false.

If you want to check for the existence of the data attribute, even if empty, do this:

if (typeof $("#dataTable").data('timer') !== 'undefined') {

Solution 2:

if (typeof $("#dataTable").data('timer') !== 'undefined')
    // your code here

Solution 3:

In the interest of providing a different answer from the ones above; you could check it with Object.hasOwnProperty(...) like this:

 if( $("#dataTable").data().hasOwnProperty("timer") ){
     // the data-time property exists, now do you business! .....

alternatively, if you have multiple data elements you want to iterate over you can variablize the .data() object and iterate over it like this:

Related:  React-Native: Application has not been registered error
 var objData = $("#dataTable").data();
 for ( data in objData ){
      if( data == 'timer' ){
            // the do

Not saying this solution is better than any of the other ones in here, but at least it’s another approach…

Solution 4:

You can use jQuery’s hasData method.

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, always returns a data object to the caller, creating one if no data object previously existed.

This will only check for the existence of any data objects (or events) on your element, it won’t be able to confirm if it specifically has a “timer” object.

Solution 5:

Or combine with some vanilla JS

if ($("#dataTable").get(0).hasAttribute("data-timer")) {

Solution 6:

If you want to distinguish between empty values and missing values you can use jQuery to check like this.

<div id="element" data-foo="bar" data-empty=""></div>

"foo" in $('#element').data(); // true
"empty" in $('#element').data(); // true
"other" in $('#element').data(); // false

So from the original question you’d do this.

if("timer" in $("#dataTable").data()) {
  // code