Explain Codes LogoExplain Codes Logo

How can I get the values of data attributes in JavaScript code?

javascript
event-handlers
data-attributes
javascript-techniques
Anton ShumikhinbyAnton Shumikhin·Feb 10, 2025
TLDR

When the clock's ticking, this is your fast pass. Use the HTML Element.dataset property or getAttribute() method to retrieve data attributes. Say you have <div id="myDiv" data-key="123"></div>:

let div = document.getElementById('myDiv'); // Space invaders! Direct access to data-* attribute let keyValue = div.dataset.key; // "123" is the launch code! // Alternative route, especially for non-standard attribute names let keyValue2 = div.getAttribute('data-key'); // Still "123"

The dataset.key property corresponds to the data-key attribute. Opt for dataset for a simple, streamlined approach and getAttribute() for broader compatibility.

Advanced techniques and considerations

Parsing numerical data attributes

When your data attributes are numerical, best buddies parseInt() or parseFloat() step in to convert them to their true forms:

// parseInt to the rescue, converting "123" to 123 let numericValue = parseInt(div.dataset.key, 10);

Watch your case: camelCasing with dataset

In dataset, we play the camelCase game. data-user-id becomes dataset.userId. Be aware of this when naming attributes:

// Decrypting the user's secret ID let userId = div.dataset.userId;

Making data attributes react with event handlers

Spice up your web page with dynamic actions! Attach an event listener to interact with data attributes:

// Click and reveal their secret! div.addEventListener('click', function() { alert('Bingo! Your data-key value is ' + this.dataset.key); });

Creating and digesting complex data attributes

For storing an object into a data attribute, JSON.stringify() is your secret weapon:

div.setAttribute('data-user', JSON.stringify({name: "Jane", age: 30}));

To retrieve and utilize that object data, use JSON.parse():

// Wake up, Jane! let userData = JSON.parse(div.dataset.user);

Old school: getAttribute for older browsers

If you're dealing with older browsers that can't handle dataset, getAttribute() is like the classics rock:

// Classics never die let keyValue3 = div.getAttribute('data-key');

Singling out elements by data attribute

With document.querySelector or document.querySelectorAll, you can target elements based on their data attributes:

// The 'one' with the key "123" const OnePunchElement = document.querySelector('div[data-key="123"]'); // The crowd with a 'category' const CrowdOfElements = document.querySelectorAll('div[data-category]');

Debugging using console

If you ever need to verify your work, remember console.log is the detective you need. Trust me, it's an excellent debugging tool:

// Will the real Slim Shady please stand up? console.log(div.dataset.key); // Logs "123" to his diary

Event handlers: your context-sensitive ally

Inside event handlers, this.dataset points to the dataset of the triggering element. It's context-sensitive, making it a true companion:

div.addEventListener('click', function() { // Sherlock Holmes in action console.log(this.dataset.key); // Outs the incognito data-key value of the clicked div. });

Dynamic data attributes manipulation

Changing data attribute values on the fly

Want to update a data attribute, just assign a new value to element.dataset.attributeName:

// Presto-change-o! data-key turns into "456" div.dataset.key = "456";

Vanishing act: removing data attributes

To remove a data attribute, set the stage with the delete operator:

// Alakazam! data-key is vanished into thin air delete div.dataset.key;

Breathing life with data attributes and CSS selectors

Data attributes can be potent when styled with CSS selectors. Dust off your stylist skills with this magical combo and watch your page come alive:

// Green means go! div[data-key='123'] { background: green; }

Invest time with MDN and other resources

To take you deeper into this world of data attributes, use the references below, especially the MDN web docs. They open new doors of understanding and shed light on every corner of this fascinating realm.