JQuery $ .data () conditional expression

I use the html5 "data" attribute for an element, and I want to assign the attribute value to a variable only if it exists and if it is not empty:

var xxx = $(this).data('what') ? $(this).data('what') : 'default_value';

but that will not work. I always get the default value ...

+4
source share
3 answers

Using a short circuit is simpler and more efficient:

 var xxx = $(this).data('what') || 'default_value'; 

But your code should have worked in any case if the data existed (as the commentator noted).

+5
source

It seems that $ (this) is not what you expect. Other than that, the expression looks great. Demo

+3
source

According to the documentation:

.data ()

The .data () method allows us to attach data of any type for DOM elements in a way that is safe from circular references and, therefore, from Leak memory.

.attr ()

The .attr () method receives the attribute value only for the first element in a consistent set.

So you want to use the .attr () method, for example:

 var xxx = $(this).attr('data-what') || 'default_value'; 
+2
source

All Articles