English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The data() method stores arbitrary data in the selected element or retrieves data from it.
When using the data() methodObtainWhen data is retrievedThe first selected elementdata.
When the data() method is used forStorageWhen data is stored toAll selected elements.
To delete data, useremoveData()Method.
Return the stored data of the selected element:
$(selector).data(key)
Store data in the selected element:
$(selector).data(key, value)
Store data using an object in the selected element:
$(selector).data(key, object)
Retrieve data from the first list item:
$("#btn1").click(function(){ alert($("li").data("price")); });Test and see‹/›
Store data in the DIV element and then retrieve the data:
// Store data $("#btn1").click(function(){ $("div").data("msg", "Hello World"); }); // Get data $("#btn2").click(function(){ $("div").text($("div").data("msg")); });Test and see‹/›
Store data using an object in the DIV element and then retrieve the data:
$("button").click(function(){ $("div").data("test", {first: 16, last: "pizza!"}); $("span:first").text($("div").data("test").first); $("span:last").text($("div").data("test").last); });Test and see‹/›
Retrieve the "data video" attribute through the button:
$("#videoModal").on("show.bs.modal", function(event) { let button = $(event.relatedTarget); // Button to trigger modal let url = button.data("video"); // From data-Extract URL from video properties $(this).find("iframe").attr({ src: url, allow: "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" }); });Test and see‹/›
Parameter | Description |
---|---|
key | Specify the key (name) of the data to be set |
value | Specify the data value to be set |
object | The key-value data object needs to be updated |