Skip to content

data() function possible bug or stupid intend? #3158

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Assassinbeast opened this issue Jun 11, 2016 · 2 comments
Closed

data() function possible bug or stupid intend? #3158

Assassinbeast opened this issue Jun 11, 2016 · 2 comments

Comments

@Assassinbeast
Copy link

Description

When using the data() function, then jQuery will get the attribute value if it doesn't exist, and get the data and NOT attribute value if it doesn't exist.

Heres an example:

If you fire $("div").data("foo");, then it will return "house".
That makes you believe that the data("foo") function is linked to the data-foo attribute in the DOM.

So if you set it now like this: $("div").data("foo", "bike");
Now you think that the data-foo attribute value is "bike", haha, thats not the case, its still "house".

So now, to get the attribute data-foo, you need to write $("div").attr("data-foo");
And to get the foo data in the code that i set, then i need to go for $("div").data("foo").

That is EXTREMELY error prone, because there could be name classes between the $("div").data("foo") and the $("div").attr("data-foo");

An example could be if you wanted to check if a key/value pair is undefined in the data(). But it is defined if the DOM object has the attribute and it is undefined if it doesn't have that attribute.

I figured it out when i was coding, and i expected something to be undefined, but it was defined because i had the same data-XXX attribute name as i had in the data("XXX") jQuery function. And then all the bug hell broke lose.

Is this a bug or a stupid intend? I think its very error-prone.

Link to test case

https://jsfiddle.net/ahmdgm1r/

@dmethvin
Copy link
Member

The API documentation explains how this works.

@yairEO
Copy link

yairEO commented Jul 13, 2016

@ Assassinbeast - I think you are the only one that's confused about this... it's been around for years and works as expected, and with good logic behind.

You need to change the way you think when you code, that's all.
seems like you get confused over some basic matters.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

3 participants