Alex
Alex

Reputation: 68036

jQuery $.data() conditional statement

I'm using the html5 "data" attribute on a element, and I want to assign the attribute value to a variable only if it exists and if it's not empty:

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

but it doesn't work. I always get the default value...

Upvotes: 4

Views: 884

Answers (3)

Jamie Treworgy
Jamie Treworgy

Reputation: 24344

Using a short circuit is simpler and more efficient:

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

But your code should have worked anyway, assuming the data existed (as the commenter noted).

Upvotes: 5

amit_g
amit_g

Reputation: 31250

Looks like $(this) is not what you expect it to be. Other than that, the statement looks fine. Demo

Upvotes: 3

Shaz
Shaz

Reputation: 15867

According to the documentation:

.data()

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

.attr()

The .attr() method gets the attribute value for only the first element in the matched set.

So what you want is to use the .attr() method, like this:

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

Upvotes: 2

Related Questions