Take the 2-minute tour ×

I am trying to add a HTML 5 data attribute into the DOM. I have seen on the jQuery site the format for data attributes is:

$('.pane-field-related-pages ul').data("role") === "listview";

But this doesnt seem to add anything into the DOM?

How can I add the above data-role into the related ul tag?

share|improve this question
The Strict comparison operator === is not for setting data, it's for checking if the two strings are strictly equal (same sequence of characters, same length, and same characters in corresponding positions) You need to use the notation as provided by diEcho to SET attributes –  Mvision May 10 '11 at 12:13
add comment

3 Answers

Read this article

From article

jQuery.com - "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."

With the introduction of HTML5, we can use it as attribute as well. For example


//We can call it via:
$("div").data("role") = "page";
$("div").data("hidden") = true;
$("div").data("options").name = "John";

alternate way

$("div").data("role", "page");
$("div").data("hidden", "true");
$("div").data("role", {name: "John"});
share|improve this answer
You're checking on equality, not doing an assignment. Same issue for the OP –  ScottE May 10 '11 at 12:12
@ScottE corrected now. thanks –  diEcho Jul 4 '13 at 5:45
@diEcho I edited your answer because it took me some time to understand what's going on when I was reading the original version. Hope you'll like my edits. –  Sandman4 Nov 18 '13 at 8:23
Thank you @Sandman4 –  diEcho Nov 19 '13 at 5:43
but my edits were rejected... not sure what to do now... –  Sandman4 Nov 19 '13 at 8:01
add comment

According to the documentation for .data() in the Jquery API, you need to do this to set it:

$('.pane-field-related-pages ul').data("role", "listview");

And this to check it:

share|improve this answer
add comment

In complement to diEcho response you have 2 data() methods in jQuery.

The first one is detailled in @diEcho response, you apply .data() to a jQuery selection, it's a getter with one arguiment and a setter with more than one argument.

The second method is jQuery.data(), applied directly to jQuery. It takes one more argument in first position, the DOM element (if you have a jQuery selection do a get(0) you get the DOM element).

share|improve this answer
add comment

Your Answer


