jQuery - How to add HTML 5 data attributes into the DOM

Adi picture Adi · May 10, 2011 · Viewed 23k times · Source

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?

Answer

diEcho picture diEcho · May 10, 2011

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

<div data-role="page" data-hidden="true" data-options='{"name":"John"}'></div>


//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"});