Explain Codes LogoExplain Codes Logo

How to set data attributes in HTML elements

javascript
data-attributes
javascript-attributes
dom-manipulation
Anton ShumikhinbyAnton ShumikhinยทJan 23, 2025
โšกTLDR

To set data attributes in HTML, use data-*="value". Here's a sample:

<div data-user-id="12345"></div> <!-- Some user ID, could be yours, who knows ๐Ÿ˜ -->

To access these attributes using vanilla JavaScript, use the element.dataset.* syntax:

let userId = document.querySelector('div').dataset.userId; // And voila! UserId is here.

To change a data attribute in HTML using jQuery, use the .attr():

$('#mydiv').attr('data-myval','60'); // MyVal is suddenly 60 now. Magic?

A light approach with JavaScript

To integrate data-* attributes using jQuery, the .attr() method is the recipe for success:

$('#dynamicElement').attr('data-role', 'button'); // Now, you're a button. Life is quick.

In plain JavaScript, you'll be using the dataset property:

document.getElementById('dynamicElement').dataset.role = 'button'; // And you're a button too!

Remember, naming conventions are key. data-* attributes are converted to camelCase in the dataset property.

Learn the ropes: DOM and jQuery synchronisation

Synchronizing DOM and jQuery's internal cache for data attributes is vital {

$('#mydiv').data('myval', 20) // Updates cache, HTML is like: huh? ๐Ÿค” $('#mydiv').attr('data-myval', 20) // Updates the HTML. Oh, now I get it! ๐Ÿ™Œ

For both worlds to catch up, chain the methods like so:

$('#mydiv').data('myval', 20).attr('data-myval', 20); // Now that's team work! ๐Ÿค

Trials and victories: Retrieving and deleting data attributes

Retrieving the value of a data attribute in jQuery is simple, use .data()

let myVal = $('#mydiv').data('myval'); // MyVal returns from the void! ๐ŸŽฉ๐Ÿ‡

To delete a data attribute, get that red marker out:

For JavaScript:

delete element.dataset.myval; // Goodbye MyVal, we hardly knew ye... element.removeAttribute('data-myval'); // Another good way to say goodbye

In the world of jQuery, .removeAttr() is your friend:

$('#myElement').removeAttr('data-myval'); // MyVal, you're fired! ๐Ÿ‘‰

Wandering into uncharted territories: Naming conflicts

Naming conflicts arrive like unexpected guests. In jQuery, beware: names starting with an underscore are reserved for its private party ๐Ÿฅณ:

$('#mydiv').data('_myval', 20); // Stay away from the VIP area ๐Ÿ˜‰

Vanilla or jQuery? A choice of flavor

Depending on your taste, choose between vanilla JavaScript's dataset and jQuery. Modern, lean, and cool as a cucumber? dataset is your star. Want extra features? Say hello to jQuery!