Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 686
Adi Avatar asked May 10 '11 12:05

Adi


People also ask

How add data attribute in HTML using jQuery?

$('div'). attr('data-info', 1); $('div')[0]. setAttribute('data-info',1); In order to access an element with the attribute set, you can simply select based on that attribute as you note in your post ( $('div[data-info="1"]') ), but when you use .

How get multiple data attribute values in jQuery?

var data = $(". menu-data"). attr("data-title");

How do you add data attribute to HTML?

Adding a data attribute is easy. Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.

Can an element have multiple data attributes?

A data attribute is a custom attribute that stores information. Data attributes always start with “data-” then followed with a descriptive name of the data that is being stored. You can have multiple data attributes on an element and be used on any HTML element.


2 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

<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"});
like image 195
diEcho Avatar answered Oct 18 '22 19:10

diEcho


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:

$('.pane-field-related-pages ul').data("role");
like image 39
Loren Avatar answered Oct 18 '22 19:10

Loren