Is there a way that I can check if a data attribute exists?
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') {
...
}
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...
if (typeof $("#dataTable").data('timer') !== 'undefined')
{
// your code here
}