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?
$('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 .
var data = $(". menu-data"). attr("data-title");
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.
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.
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";
$("div").data("role", "page");
$("div").data("hidden", "true");
$("div").data("role", {name: "John"});
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With