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

JavascriptJquery

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

NOTE this only returns true if the data attribute is not empty string or a "falsey" value e.g. 0 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 - Javascript

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

Solution 3 - Javascript

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:

 var objData = $("#dataTable").data();
 for ( data in objData ){
      if( data == 'timer' ){
            //...do 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 - Javascript

Or combine with some vanilla JS

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

Solution 5 - Javascript

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>

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

So from the original question you'd do this.

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

Solution 6 - Javascript

All the answers here use the jQuery library.

But the vanilla javascript is very straightforward.

If you want to run a script only if the element with an id of #dataTable also has a data-timer attribute, then the steps are as follows:

// Locate the element
const myElement = document.getElementById('dataTable');

// Run conditional code
if (myElement.dataset.hasOwnProperty('timer')) {

  [... CODE HERE...]

}

Solution 7 - Javascript

You can use jQuery's hasData method.

http://api.jquery.com/jQuery.hasData/

> 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.

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 8 - Javascript

You can create an extremely simple jQuery-plugin to query an element for this:

$.fn.hasData = function(key) {
  return (typeof $(this).data(key) != 'undefined');
};

Then you can simply use $("#dataTable").hasData('timer')

Gotchas:

  • Will return false only if the value does not exist (is undefined); if it's set to false/null it hasData() will still return true.
  • It's different from the built-in $.hasData() which only checks if any data on the element is set.

Solution 9 - Javascript

This is the easiest solution in my opinion is to select all the element which has certain data attribute:

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(', '));
Here is the screenshot of how it works.

console log of the jquery selector

Solution 10 - Javascript

I've found this works better with dynamically set data elements:

if ($("#myelement").data('myfield')) {
  ...
}

Solution 11 - Javascript

You can check by css attribute selection with

if ($('#dataTable').is('[data-timer]')) {
   // data-timer attribute exists
}

Solution 12 - Javascript

Wrong answer - see EDIT at the end

Let me build on Alex's answer.

To prevent the creation of a data object if it doesn't exists, I would better do:

$.fn.hasData = function(key) {
    var $this = $(this);
    return $.hasData($this) && typeof $this.data(key) !== 'undefined';
};

Then, where $this has no data object created, $.hasData returns false and it will not execute $this.data(key).

EDIT: function $.hasData(element) works only if the data was set using $.data(element, key, value), not element.data(key, value). Due to that, my answer is not correct.

Solution 13 - Javascript

I needed a simple boolean to work with. Because it's undefined of not present, and not false, I use the !! to convert to boolean:

var hasTimer = !!$("#dataTable").data('timer');
if( hasTimer ){ /* ....... */ }

An alternative solution would be using filter:

if( $("#dataTable").filter('[data-timer]').length!==0) { /* ....... */ }

Solution 14 - Javascript

var data = $("#dataTable").data('timer');
var diffs = [];

if( data.length > 0 ) {
for(var i = 0; i + 1 < data.length; i++) {
    diffs[i] = data[i + 1] - data[i];
}

alert(diffs.join(', '));
}

Solution 15 - Javascript

And what about:

if ($('#dataTable[data-timer]').length > 0) {
    // logic here
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAngelaView Question on Stackoverflow
Solution 1 - JavascriptniiruView Answer on Stackoverflow
Solution 2 - JavascriptPaul FlemingView Answer on Stackoverflow
Solution 3 - JavascriptsadmicrowaveView Answer on Stackoverflow
Solution 4 - JavascriptMaxView Answer on Stackoverflow
Solution 5 - JavascriptRyanView Answer on Stackoverflow
Solution 6 - JavascriptRounin - Standing with UkraineView Answer on Stackoverflow
Solution 7 - JavascriptBZinkView Answer on Stackoverflow
Solution 8 - JavascriptAlexView Answer on Stackoverflow
Solution 9 - JavascriptAnimesh SinghView Answer on Stackoverflow
Solution 10 - JavascriptJerSchneidView Answer on Stackoverflow
Solution 11 - JavascriptacmeView Answer on Stackoverflow
Solution 12 - JavascriptnestorrenteView Answer on Stackoverflow
Solution 13 - JavascriptMartijnView Answer on Stackoverflow
Solution 14 - JavascriptLuceosView Answer on Stackoverflow
Solution 15 - Javascriptdani24View Answer on Stackoverflow