Explain Codes LogoExplain Codes Logo

Adding data attribute to DOM

javascript
prompt-engineering
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Nov 7, 2024
TLDR

There are two ways to attach a data attribute to an HTML element using JavaScript:

//using the dataset property element.dataset.myAttribute = 'someValue'; //creates data-my-attribute="someValue" // or // using the setAttribute() method element.setAttribute('data-my-attribute', 'someValue'); //the more old-school way

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.

$('#element').data('myAttribute', 'spankinNewValue'); //updates only jQuery's internal data $('#element').attr('data-my-attribute', 'spankinNewValue'); //changes the actual DOM attribute

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:

$('<div/>').attr('data-my-attribute', 'someValue').appendTo('body'); //adding a tag that says 'Handle with care!'

When you have to select these elements later, use attribute selectors:$('div[data-my-attribute="someValue"]').

var $dynamicElement = $('div[data-my-attribute="value"]'); //fetches your lost luggage from the 'DOM' carousel

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.

// Setting $('#dynamicElement').attr('data-newAttribute', '123'); //Tagging fresh elements // Accessing var dataValue = $('#dynamicElement').attr('data-newAttribute'); //Playing tag with JavaScript

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.

var $element = $('#element'); $element.data('myAttribute', 'new-value').attr('data-my-attribute', 'new-value'); //Beats having to remember where you kept things

Changing content based on data attributes

You can select elements based on their data attribute and update their content using .attr() with .text():

$('div').filter(function() { return $(this).attr('data-my-attribute') === '1'; }).text('Updated content'); //Just like changing clothes according to the weather

Direct manipulation with .setAttribute(), .dataset

Vanilla JavaScript is flexible enough. Sometimes, doing direct DOM manipulation using .setAttribute() or .dataset is faster:

document.getElementById('element').dataset.info = 'new-info'; //When the jQuery flavour gets too strong

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:

document.querySelector('[data-destination="Paris"]').innerText = 'Bonjour'; //sets text content. Oui, très bien! document.querySelector('[data-destination="Paris"]').innerHTML = '<strong>Bonjour</strong>'; //boldly sets HTML content. Impressionnant!