Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 913
Angela Avatar asked Aug 28 '12 14:08

Angela


People also ask

How do you check data is exist or not in jQuery?

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 .

How do you check if an element has an attribute in jQuery?

Using jQuery The idea is to use the . attr() method, which returns the attribute's value for an element if it is present and returns undefined if the attribute doesn't exist.


1 Answers

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') {   ... } 
like image 61
niiru Avatar answered Sep 17 '22 03:09

niiru