How to set data attributes in HTML elements
To set data attributes in HTML, use data-*="value"
. Here's a sample:
To access these attributes using vanilla JavaScript, use the element.dataset.*
syntax:
To change a data attribute in HTML using jQuery, use the .attr()
:
A light approach with JavaScript
To integrate data-*
attributes using jQuery, the .attr()
method is the recipe for success:
In plain JavaScript, you'll be using the dataset
property:
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 {
For both worlds to catch up, chain the methods like so:
Trials and victories: Retrieving and deleting data attributes
Retrieving the value of a data attribute in jQuery is simple, use .data()
To delete a data attribute, get that red marker out:
For JavaScript:
In the world of jQuery, .removeAttr()
is your friend:
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 ๐ฅณ:
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!
Was this article helpful?