Adding data attribute to DOM
There are two ways to attach a data attribute
to an HTML element using JavaScript:
Remember, element
here is the HTML element you want to add the data attribute to, and 'someValue'
is the value you want for that attribute.
jQuery, .data(), and .attr()
With jQuery, the .data('myAttribute', 'someValue')
method is the simplest, since it directly interfaces with its data management system. But, here's the rub: .data()
does not reflect changes in the actual HTML DOM attributes, it only updates the internal jQuery data object.
If you need to manipulate the HTML data attribute
(for data-driven styling or attribute selectors), .attr()
is your knight in shining armor.
Always use.data()
to retrieve data set using .data()
, because jQuery handles type conversions
for you. Handy, isn't it?
Dealing with dynamic elements
For dynamically generated elements, you need to use .attr()
or .dataset
to make sure they grace the DOM with their presence:
When you have to select these elements later, use attribute selectors:$('div[data-my-attribute="someValue"]')
.
Consistency with .attr()
Both setting and retrieving values of data attributes on dynamic elements with .attr()
offers more consistency. It directly reflects the changes in the DOM.
Synchronizing .attr() and .data()
If you need your changes to show up in the DOM, as well as in jQuery’s internal data storage, use .attr()
and .data()
together.
Changing content based on data attributes
You can select elements based on their data attribute
and update their content using .attr()
with .text()
:
Direct manipulation with .setAttribute(), .dataset
Vanilla JavaScript is flexible enough. Sometimes, doing direct DOM manipulation using .setAttribute()
or .dataset
is faster:
Quick updates with .innerText and .innerHTML
Looking for a quick way to update text content or HTML of an element identified by its data attribute?.innerText
and .innerHTML
come to rescue:
Was this article helpful?