4

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...

3
  • 1
    are you sure that data-what exists at any point? Commented Apr 28, 2011 at 16:12
  • 1
    Have you outputted the conditional part of the statement to see whether it can actually resolve to true and false? If not, change your conditional so it works. Commented Apr 28, 2011 at 16:13
  • ok, the problem was $(this) was something else than what I was expecting :) sorry for being dumb :x Commented Apr 28, 2011 at 16:38

3 Answers 3

5

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).

Sign up to request clarification or add additional context in comments.

6 Comments

loooove doing this. Beat me to the answer :p
jQuery treats data-* attributes as .data(). See @amit_g's demo.
@Rocket, didn't know that. I removed my caveat. Does it actually store the data as an attribute now? If not, what happens if you update the data but not the attribute?
So basically it copies the data-* values on first access but they are out of sync once changes are made through $.data.
do you guys know what value will have $(this).data('what'); if there is no data-what attribute?
|
3

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

Comments

2

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';

2 Comments

jQuery treats data-* attributes as .data(). See @amit_g's demo.
@Rocket: Using .attr() for this is faster. Check out jsperf.com/data-vs-attr

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.