How to get and set element data using jQuery's data() method?

To get and set element data using jQuery's data() method, you can follow these steps:

  1. To get the value of an element's data attribute:
// Syntax: $(selector).data(attributeName) // Get the data attribute value of an element var value = $('selector').data('dataAttributeName');
  1. To set the value of an element's data attribute:
// Syntax: $(selector).data(attributeName, value) // Set the data attribute value of an element $('selector').data('dataAttributeName', value);

Here's an example of setting and getting an element's data attribute:

HTML:

<div id="element" data-mydata="example"></div>

JavaScript:

// Get the value of data attribute var value = $('#element').data('mydata'); console.log(value); // Output: example // Set the value of data attribute $('#element').data('mydata', 'newvalue'); // Get the updated value of data attribute var updatedValue = $('#element').data('mydata'); console.log(updatedValue); // Output: newvalue

In this example, the initial value of the data attribute "mydata" is "example". We use the data() method to get the value and then set it to "newvalue". After updating the value, we again use the data() method to get the updated value, which is "newvalue".