You can try the following:
var folderID = $(this).attr('data-id') || 1;
JS Fiddle demo
The above assigns the data-attribute value to the folderID variable, if the selector does not return a match, then it assigns a default value of 1 .
In 2016 and, quite possibly, from 2015, instead, you can use several ways to get the data-id attribute using the DOM - as well as jQuery - these parameters are below:
var folderID = $(this).data('id'); // jQuery var folderID = this.dataset.id; var folderID = this.getAttribute('data-id');
Obviously, all of them require that this be the appropriate element from which you want to get the attribute value.
The comment below indicates an obvious flaw in the above:
Note that if you have a data-id of 0, the value 1 will be used instead (0 is the false value).
With this in mind, itβs worth revising the problem, showing a very similar solution, but using the data-id check:
var folderID = 'undefined' !== typeof this.dataset.id ? this.dataset.id : 1;
In the above example, we check if the type ( typeof ) of the reference property ( !== ) is undefined ; if it is not equal to undefined , we retrieve the value stored in this property (the value of the this.dataset.id property is an attribute-attribute of the data-id attribute) or, if it is undefined , then we provide the value 1 .
This approach uses a conditional (triple) operator in which the expression evaluates to true / false (or truthy / falsey ), and if the expression evaluates to true / truthy then the first statement following the character is used ? . If the expression evaluates to false / falsey , then the second statement is used, following::
var variableName = expression ? ifTrue : ifFalse;
Literature: