On jQuery’s .data() Call Syntax

Posted Monday, February 22nd, 2016 at 9:10 am

I recently had a developer on my team who had some trouble with jQuery’s $(...).data() syntax. In case anyone else has trouble, maybe I can clarify things a bit. I’m anonymizing all the code involved, of course.

We wanted to make certain items have certain behaviors under certain circumstances. And so we set up a “whatToDo” data attribute, which could be any of certain values. Items with the attribute would have a class “specialItem”, to make them easy to find.

So the HTML included things like these:

<div class="specialItem" data-what-to-do="activate">Text Here</div>

<div class="specialItem" data-what-to-do="react">Text Here</div>

<div class="specialItem" data-what-to-do="solidify">Text Here</div>

So far, we only care about when it’s set to activate; the other values are for future extensibility. So my co-worker checked in code that read:

$(".specialItem").each(function() {
    if ($(this).data("data-what-to-do") == "activate") {
        // set it up as desired

In my co-worker’s defense, the setup code that I’ve elided with a comment actually involved a call to a poorly-understood third-party API that we had every reason to expect might prove somewhat difficult. So when he tested and found things not working, he immediately assumed there was something wrong in his third-party call and came to me for help with that.

But I looked at his data() call and pointed out that that was where his problem really was. Because data("data-what-to-do") will always return undefined. And that’s because the leading data- is not part of the name.

Calling data("data-what-to-do") will try to retrieve a value from the HTML <div class="specialItem" data-data-what-to-do="activate"> — note that double “data” there.

In fact, because the attribute names get their dashes converted to CamelCase, as described in various spec documents, you actually want to use data("whatToDo") to read the data-what-to-do attribute. The code should be:

if ($(this).data("whatToDo") == "activate")

It turns out that current versions of jQuery will actually throw you a bone if you don’t realize the CamelCasing thing. The following will work, even though it shouldn’t:

if ($(this).data("what-to-do") == "activate")

But putting that leading data- on it will make it fail.


Here’s the “in a nutshell” version of all this. If you’re trying to read the attribute data-what-to-do, then…

$(node).data("whatToDo") // what you really should write

$(node).data("what-to-do") // will work, even if it shouldn’t

$(node).data("data-what-to-do") // WILL FAIL

I hope someone finds this helpful.

Post a Comment

Your email is never shared. Required fields are marked *