How to Attaches data to, or gets data from, selected elements in jQuery ?


To attach data to selected elements in jQuery, we can use the .data() method. This method allows us to store arbitrary data associated with the selected elements. Here's an example:

// Attach data to a selected element
$('#my-element').data('key', 'value');

// Retrieve data from a selected element
var value = $('#my-element').data('key');
console.log(value); // Output: "value"

In the example above, we attach the data "value" to the element with the ID "my-element" using the .data() method. We can then retrieve the data using the same method and passing in the key "key".

Alternatively, we can also use the .attr() method to attach data to selected elements. However, this method is less flexible than .data() as it can only store string values. Here's an example:

// Attach data to a selected element using .attr()
$('#my-element').attr('data-key', 'value');

// Retrieve data from a selected element using .attr()
var value = $('#my-element').attr('data-key');
console.log(value); // Output: "value"

In this example, we attach the data "value" to the element with the ID "my-element" using the .attr() method. We can then retrieve the data using the same method and passing in the attribute name "data-key".

Overall, using the .data() method is the recommended way to attach data to selected elements in jQuery as it provides more flexibility and better performance.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.