How To Manage Custom Data Of Element Using dataset

By bhagwatchouhan
How To Manage Custom Data Of Element Using dataset

We need to store or associate custom data specific to an element in order to do processing e.g. get the database mapped id or name associated with the data. This data can be used to send an update request to the server by AJAX/WebSocket call. The exact processing depends on the actual requirements, but storing data using data attributes is really handy in several situations.

The dataset property on the HTMLElement interface provides access to either read or write the custom data using data-* attributes where * is the hyphen separated name corresponding to the camel case name. We can read the dataset property, but can't write it directly. The write operations have to be performed on the attributes as shown below.

// Some of the data values are already filled
<div id="department" data-id="124120" data-org="mycorp" data-name="finance" data-total-members="125" data-status>Finance Department</div>

The above div element corresponds to a department within an organization with custom attributes including id, org, name, totalMembers, and status where all the custom values are already set except the status. We can read or write these data attributes as mentioned below.

// Get the element
var dept = document.querySelector( '#department' );

// Read the attributes
var id = dept.dataset.id;
var org = dept.dataset.org;
var name = dept.dataset.name;
var totalMembers = dept.dataset.totalMembers; // Access the hyphenated data attribute using camel case naming convention
var status = dept.dataset.status;

// Set status attribute
dept.dataset.status = 'active';

// Update name
dept.dataset.name = 'Finance';

// Delete member count attribute
delete dept.dataset.totalMembers;

An example pen on codepen is as shown below.

Share this blog:

Profile picture for user bhagwatchouhan
bhagwatchouhan