The dataset
read-only property
of the HTMLElement
interface provides read/write access to custom data attributes
(data-*
) on elements. It exposes a map of strings
(DOMStringMap
) with an entry for each data-*
attribute.
Note: The dataset
property itself can be read, but not directly written.
Instead, all writes must be to the individual properties within the
dataset
, which in turn represent the data attributes.
An HTML data-*
attribute and its corresponding DOM
dataset.property
modify their shared name according to where
they are read or written:
- In HTML
-
The attribute name begins with
data-
. It can contain only letters,
numbers, dashes (-
), periods (.
), colons (:
),
and underscores (_
). Any ASCII capital letters (A
to
Z
) are converted to lowercase. - In JavaScript
-
The property name of a custom data attribute is the same as the HTML attribute
without thedata-
prefix, and removes single dashes (-
) for
when to capitalize the property’s «camelCased» name.
In addition to the information below, you’ll find a how-to guide for using HTML data
attributes in our article Using data attributes.
Name conversion
dash-style
tocamelCase
conversion-
A custom data attribute name is transformed to a key for the
DOMStringMap
entry by the following:-
Lowercase all ASCII capital letters (
A
to
Z
); - Remove the prefix
data-
(including the dash); -
For any dash (
U+002D
) followed by an ASCII lowercase letter
a
toz
, remove the dash and uppercase the letter; - Other characters (including other dashes) are left unchanged.
-
Lowercase all ASCII capital letters (
camelCase
todash-style
conversion-
The opposite transformation, which maps a key to an attribute name, uses the
following:-
Restriction: Before transformation, a dash must not be
immediately followed by an ASCII lowercase lettera
to
z
; - Add the
data-
prefix; -
Add a dash before any ASCII uppercase letter
A
toZ
,
then lowercase the letter; - Other characters are left unchanged.
-
Restriction: Before transformation, a dash must not be
For example, a data-abc-def
attribute corresponds to
dataset.abcDef
.
Accessing values
-
Attributes can be set and read by the camelCase name/key as an object property of
the dataset:element.dataset.keyname
. -
Attributes can also be set and read using bracket syntax:
element.dataset['keyname']
. -
The
in
operator can check if a given attribute exists:
'keyname' in element.dataset
.
Setting values
-
When the attribute is set, its value is always converted to a string.
For example:element.dataset.example = null
is
converted intodata-example="null"
. - To remove an attribute, you can use the
delete
operator:delete element.dataset.keyname
.
Value
Examples
<div id="user" data-id="1234567890" data-user="carinaanand" data-date-of-birth>
Carina Anand
</div>
const el = document.querySelector('#user');
// el.id === 'user'
// el.dataset.id === '1234567890'
// el.dataset.user === 'carinaanand'
// el.dataset.dateOfBirth === ''
// set a data attribute
el.dataset.dateOfBirth = '1960-10-03';
// Result on JS: el.dataset.dateOfBirth === '1960-10-03'
// Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand" data-date-of-birth="1960-10-03">Carina Anand</div>
delete el.dataset.dateOfBirth;
// Result on JS: el.dataset.dateOfBirth === undefined
// Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand">Carina Anand</div>
if (!('someDataAttr' in el.dataset)) {
el.dataset.someDataAttr = 'mydata';
// Result on JS: 'someDataAttr' in el.dataset === true
// Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand" data-some-data-attr="mydata">Carina Anand</div>
}
Specifications
Specification |
---|
HTML Standard # dom-dataset-dev |
Browser compatibility
BCD tables only load in the browser
See also
I have a div with an attribute data-myval = "10"
. I want to update its value; wouldn’t it change if I use div.data('myval',20)
? Do I need to use div.attr('data-myval','20')
only?
Am I getting confused between HTML5 and jQuery? Please advise. Thanks!
EDIT: Updated div.data('myval')=20
to div.data('myval',20)
, but still the HTML is not updating.
asked Nov 23, 2012 at 6:29
Pulkit MittalPulkit Mittal
5,8165 gold badges20 silver badges27 bronze badges
3
HTML
<div id="mydiv" data-myval="10"></div>
JS
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data('myval',20); //setter
Demo
Reference
From the reference:
jQuery itself uses the
.data()
method to save information under the names ‘events’ and ‘handle’, and also reserves any data name starting with an underscore (‘_’) for internal use.
It should be noted that jQuery’s data()
doesn’t change the data
attribute in HTML.
So, if you need to change the data
attribute in HTML, you should use .attr()
instead.
HTML
<div id="outer">
<div id="mydiv" data-myval="10"></div>
</div>
jQuery:
alert($('#outer').html()); // alerts <div id="mydiv" data-myval="10"> </div>
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html()); //alerts <div id="mydiv" data-myval="20"> </div>
See this demo
answered Nov 23, 2012 at 6:32
JashwantJashwant
28.2k16 gold badges70 silver badges103 bronze badges
8
Vanilla Javascript solution
HTML
<div id="mydiv" data-myval="10"></div>
JavaScript:
-
Using DOM’s
getAttribute()
propertyvar brand = mydiv.getAttribute("data-myval")//returns "10" mydiv.setAttribute("data-myval", "20") //changes "data-myval" to "20" mydiv.removeAttribute("data-myval") //removes "data-myval" attribute entirely
-
Using JavaScript’s
dataset
propertyvar myval = mydiv.dataset.myval //returns "10" mydiv.dataset.myval = '20' //changes "data-myval" to "20" mydiv.dataset.myval = null //removes "data-myval" attribute
RiZKiT
1,87725 silver badges22 bronze badges
answered Nov 23, 2012 at 7:47
rajesh kakawatrajesh kakawat
10.8k1 gold badge21 silver badges40 bronze badges
You can also use the following attr
thing;
HTML
<div id="mydiv" data-myval="JohnCena"></div>
Script
$('#mydiv').attr('data-myval', 'Undertaker'); // sets
$('#mydiv').attr('data-myval'); // gets
OR
$('#mydiv').data('myval'); // gets value
$('#mydiv').data('myval','John Cena'); // sets value
answered Aug 16, 2016 at 17:12
Baqer NaqviBaqer Naqvi
5,6023 gold badges46 silver badges68 bronze badges
2
Please take note that jQuery .data()
is not updated when you change html5 data-
attributes with javascript.
If you use jQuery .data()
to set data-
attributes in HTML elements you better use jQuery .data()
to read them. Otherwise there can be inconsistencies if you update the attributes dynamically. For example, see setAttribute()
, dataset()
, attr()
below. Change the value, push the button several times and see the console.
Kirby
14.8k8 gold badges88 silver badges102 bronze badges
answered Sep 24, 2014 at 17:25
To keep jQuery and the DOM in sync, a simple option may be
$('#mydiv').data('myval',20).attr('data-myval',20);
BEingprabhU
1,5582 gold badges20 silver badges28 bronze badges
answered Jan 29, 2020 at 15:02
J. McNerneyJ. McNerney
5464 silver badges15 bronze badges
If you’re using jQuery, use .data()
:
div.data('myval', 20);
You can store arbitrary data with .data()
, but you’re restricted to just strings when using .attr()
.
answered Nov 23, 2012 at 6:31
BlenderBlender
285k52 gold badges432 silver badges490 bronze badges
14
[jQuery] .data() vs .attr() vs .extend()
The jQuery method .data()
updates an internal object managed by jQuery through the use of the method, if I’m correct.
If you’d like to update your data-attributes
with some spread, use —
$('body').attr({ 'data-test': 'text' });
— otherwise, $('body').attr('data-test', 'text');
will work just fine.
Another way you could accomplish this is using —
$.extend( $('body')[0].dataset, { datum: true } );
— which restricts any attribute change to HTMLElement.prototype.dataset
, not any additional HTMLElement.prototype.attributes
.
answered Dec 17, 2017 at 7:38
CodyCody
9,6064 gold badges60 silver badges45 bronze badges
Another way to set the data- attribute is using the dataset property.
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>
const el = document.querySelector('#user');
// el.id == 'user'
// el.dataset.id === '1234567890'
// el.dataset.user === 'johndoe'
// el.dataset.dateOfBirth === ''
// set the data attribute
el.dataset.dateOfBirth = '1960-10-03';
// Result: el.dataset.dateOfBirth === 1960-10-03
delete el.dataset.dateOfBirth;
// Result: el.dataset.dateOfBirth === undefined
// 'someDataAttr' in el.dataset === false
el.dataset.someDataAttr = 'mydata';
// Result: 'someDataAttr' in el.dataset === true
answered Aug 26, 2019 at 15:23
CloudBranchCloudBranch
1,3533 gold badges16 silver badges22 bronze badges
I have a div with an attribute data-myval = "10"
. I want to update its value; wouldn’t it change if I use div.data('myval',20)
? Do I need to use div.attr('data-myval','20')
only?
Am I getting confused between HTML5 and jQuery? Please advise. Thanks!
EDIT: Updated div.data('myval')=20
to div.data('myval',20)
, but still the HTML is not updating.
asked Nov 23, 2012 at 6:29
Pulkit MittalPulkit Mittal
5,8165 gold badges20 silver badges27 bronze badges
3
HTML
<div id="mydiv" data-myval="10"></div>
JS
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data('myval',20); //setter
Demo
Reference
From the reference:
jQuery itself uses the
.data()
method to save information under the names ‘events’ and ‘handle’, and also reserves any data name starting with an underscore (‘_’) for internal use.
It should be noted that jQuery’s data()
doesn’t change the data
attribute in HTML.
So, if you need to change the data
attribute in HTML, you should use .attr()
instead.
HTML
<div id="outer">
<div id="mydiv" data-myval="10"></div>
</div>
jQuery:
alert($('#outer').html()); // alerts <div id="mydiv" data-myval="10"> </div>
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html()); //alerts <div id="mydiv" data-myval="20"> </div>
See this demo
answered Nov 23, 2012 at 6:32
JashwantJashwant
28.2k16 gold badges70 silver badges103 bronze badges
8
Vanilla Javascript solution
HTML
<div id="mydiv" data-myval="10"></div>
JavaScript:
-
Using DOM’s
getAttribute()
propertyvar brand = mydiv.getAttribute("data-myval")//returns "10" mydiv.setAttribute("data-myval", "20") //changes "data-myval" to "20" mydiv.removeAttribute("data-myval") //removes "data-myval" attribute entirely
-
Using JavaScript’s
dataset
propertyvar myval = mydiv.dataset.myval //returns "10" mydiv.dataset.myval = '20' //changes "data-myval" to "20" mydiv.dataset.myval = null //removes "data-myval" attribute
RiZKiT
1,87725 silver badges22 bronze badges
answered Nov 23, 2012 at 7:47
rajesh kakawatrajesh kakawat
10.8k1 gold badge21 silver badges40 bronze badges
You can also use the following attr
thing;
HTML
<div id="mydiv" data-myval="JohnCena"></div>
Script
$('#mydiv').attr('data-myval', 'Undertaker'); // sets
$('#mydiv').attr('data-myval'); // gets
OR
$('#mydiv').data('myval'); // gets value
$('#mydiv').data('myval','John Cena'); // sets value
answered Aug 16, 2016 at 17:12
Baqer NaqviBaqer Naqvi
5,6023 gold badges46 silver badges68 bronze badges
2
Please take note that jQuery .data()
is not updated when you change html5 data-
attributes with javascript.
If you use jQuery .data()
to set data-
attributes in HTML elements you better use jQuery .data()
to read them. Otherwise there can be inconsistencies if you update the attributes dynamically. For example, see setAttribute()
, dataset()
, attr()
below. Change the value, push the button several times and see the console.
Kirby
14.8k8 gold badges88 silver badges102 bronze badges
answered Sep 24, 2014 at 17:25
To keep jQuery and the DOM in sync, a simple option may be
$('#mydiv').data('myval',20).attr('data-myval',20);
BEingprabhU
1,5582 gold badges20 silver badges28 bronze badges
answered Jan 29, 2020 at 15:02
J. McNerneyJ. McNerney
5464 silver badges15 bronze badges
If you’re using jQuery, use .data()
:
div.data('myval', 20);
You can store arbitrary data with .data()
, but you’re restricted to just strings when using .attr()
.
answered Nov 23, 2012 at 6:31
BlenderBlender
285k52 gold badges432 silver badges490 bronze badges
14
[jQuery] .data() vs .attr() vs .extend()
The jQuery method .data()
updates an internal object managed by jQuery through the use of the method, if I’m correct.
If you’d like to update your data-attributes
with some spread, use —
$('body').attr({ 'data-test': 'text' });
— otherwise, $('body').attr('data-test', 'text');
will work just fine.
Another way you could accomplish this is using —
$.extend( $('body')[0].dataset, { datum: true } );
— which restricts any attribute change to HTMLElement.prototype.dataset
, not any additional HTMLElement.prototype.attributes
.
answered Dec 17, 2017 at 7:38
CodyCody
9,6064 gold badges60 silver badges45 bronze badges
Another way to set the data- attribute is using the dataset property.
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>
const el = document.querySelector('#user');
// el.id == 'user'
// el.dataset.id === '1234567890'
// el.dataset.user === 'johndoe'
// el.dataset.dateOfBirth === ''
// set the data attribute
el.dataset.dateOfBirth = '1960-10-03';
// Result: el.dataset.dateOfBirth === 1960-10-03
delete el.dataset.dateOfBirth;
// Result: el.dataset.dateOfBirth === undefined
// 'someDataAttr' in el.dataset === false
el.dataset.someDataAttr = 'mydata';
// Result: 'someDataAttr' in el.dataset === true
answered Aug 26, 2019 at 15:23
CloudBranchCloudBranch
1,3533 gold badges16 silver badges22 bronze badges
Все атрибуты у HTML элементов, начинающиеся с префикса data-*, являются пользовательскими. Data атрибуты можно использовать для дополнительной стилизации, но чаще всего они применяются для создания интерактивной логики в JavaScript. Особенно их любят применять разные библиотеки, когда пользователю предлагается настроить скрипт через data атрибуты. Сделать это может любой начинающий вебмастер с начальным уровнем знаний JavaScript.
Использование data атрибутов в HTML и CSS
Data атрибут — это очень гибкий инструмент и сейчас мы рассмотрим, как можно его использовать в HTML и CSS.
Как добавить data атрибут к HTML тегу
Вначале обязательно ставим префикс data, затем через дефис указываем какое-то наше слово подходящее по смыслу и само значение. Например мы хотим отсортировать только категорию с домашними питомцами. Все слова, за исключением самого префикса data-*, мы можем придумывать свои собственные. Так мы можем управлять отдельными группами элементов, помеченные data атрибутами. Это удобно для создания интерактива на языке JavaScript.
<button data-categories="pets">Pets</button>
Длина названия data атрибута может быть любой, слова должны разделяться через дефис.
<div data-is-active-color="red"></div>
Пример стилизации элементов с data атрибутом
Мы можем стилизовать любой элемент по его data атрибуту. В CSS коде селектор data атрибута заключается в квадратные скобки. Обращаться можно только по названию атрибута, по тегу + название или по классу (id) + название.
// HTML код
<div class="large_btn" data-size="large">button</div>
// CSS код
// селектор по названию атрибута
[data-size="large"] {
font-size: 30px;
padding: 20px;
}
// селектор по тегу и названию
div [data-size="large"] {
font-size: 30px;
padding: 20px;
}
// селектор по классу и названию
large_btn.[data-size="large"] {
font-size: 30px;
padding: 20px;
}
Принцип создания подсказок с data атрибутом на CSS
Прописываем текст подсказки в data атрибуте тега. Затем с помощью псевдоэлементов ::before или ::after передать в функцию attr значение атрибута data-tooltip.
<span data-tooltip="текст подсказки"></span>
[data-tooltip]::after {
content: attr(data-tooltip);
}
Использование data атрибутов в JavaScript
В JS существует, как минимум два способа получения data атрибута:
Первый способ, через getAttribute и setAttribute
Указываем выбранный на странице элемент (тег, id, класс), сам метод getAttribute и название атрибута, который надо получить.
element.getAttribute("data-filter")
Метод setAttribute добавляет значение, указанное вторым параметром («pillows») в data атрибут в первом параметре («data-filter»).
element.setAttribute("data-filter", "pillows")
Второй способ, через объект dataset в структуре DOM
Доступ к коллекции dataset мы получаем по ключу (слово после префикса data-*).
<div data-person></div>
// Получение data атрибута
div.dataset.person
// Добавление значения для data атрибута
div.dataset.person = "Donald"
Работа с data атрибутами в JavaScript — достаточно актуальная тема, с которой вы будете часто встречаться, более основательно познакомиться с data атрибутами и не только, вы сможете в моем видеокурсе по JavaScript.
Итоги
Data атрибуты позволяют хранить разную информацию об элементе, которая может помочь для работы скриптов, а также для CSS стилизации элементов. HTML код с созданными атрибутами с data-* префиксом будет, абсолютно валидным. Создавать свои собственные data атрибуты для хранения значений стало возможным лишь в HTML5, до этого такой возможности очень не хватало веб-разработчикам. Вот список самых востребованные задач, которые удобно решать с помощью data атрибутов:
- Создание всплывающих подсказок на чистом CSS
- Получать и изменять значения атрибутов
-
Создано 16.11.2020 10:06:02
-
Михаил Русаков
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
-
Кнопка:
Она выглядит вот так:
-
Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт
- BB-код ссылки для форумов (например, можете поставить её в подписи):
One of the best ways to store data in HTML is with data attributes. These data attributes can be used to do some pretty cool things in CSS without the need for JavaScript, as seen in this article, but data attributes are most useful when combined with JavaScript. In this article I will teach you exactly how to use data attributes in JavaScript and what makes them so powerful.
Data Attribute Introduction
To get started talking about data attributes we need to first have some HTML with data attributes. To create a data attribute in HTML we just need to add a custom attribute to our HTML element that starts with data-
.
Reading Data Attributes
We now have a div with three custom data attributes. Now let’s move over to JavaScript to see how we would access these data attributes.
The dataset
property on an element will return a DOMStringMap
which is essentially just an object that contains all the custom data attributes of an element. Our dataset
looks like this.
You will notice two interesting things about this.
First, all of our properties are converted from snake case, first-name
, to camel case, firstName
. This is because in JavaScript object properties are primarily written as camel case so this just makes working with the JavaScript object much easier.
Second, the active
property has a value of ""
. This is because any data attribute without a value is assumed to have an empty string as its value.
Now in order to access an individual data attribute we just access it like a property on an object since dataset
is just an object.
Writing Data Attributes
In order to create a new data attribute in JavaScript we just need to add a new property to the dataset
object with a value.
This will update the dataset object and our HTML which means our HTML will look like this.
Updating Data Attributes
Let’s say that we now want to update the value of a data attribute. This is incredibly easy since it works just like a normal object. We just need to set the value of our dataset
property to the new value and it will update the HTML for us.
This will update the dataset object and our HTML which means our HTML will look like this.
Delete Data Attributes
Deleting data attributes is a bit different since we need to actually remove the property from our object. This is because if we try setting the value to undefined
or null
the dataset
object will still have a reference to that property with that value of undefined
or null
and will set the value of our HTML data attribute to the string null
or undefined
.
To delete an element we need to use the delete
keyword to remove it completely from the object.
This will update the dataset object and our HTML which means our HTML will look like this.
Real World Example
Now let’s combine all this into a real world example. Let’s say you have the following HTML.
You want to write JavaScript so that the first button opens modal 1 and the second button opens modal 2, but we want to do this in a way that is reusable so if we add a third button that opens a new modal we don’t need to write any new JavaScript code.
This may sound really difficult at first, but essentially all we need is some way to link each button to their respective modal in the HTML. This is where data attributes come in.
We can set a custom data attribute on each button that references the modal they are linked to. In our case we can use the id of each modal as our reference.
So now we have a way to access the id of the modal linked to each button inside JavaScript.
In the above code we are selecting all elements that contain our custom data-modal-id
attribute. We are then looping through them and adding a click event listener to each one. Inside this event listener we are using the modal id to get the modal link to that button and adding the show class so it is now visible.
This code is also flexible since it will get any element with the custom data-modal-id
attribute. This means that if we add a new button that references a new modal we won’t need to write any additional JavaScript.
Conclusion
Data attributes in JavaScript are incredibly useful. They allow you to write extremely flexible code which means you can spend more time writing the HTML for your project and less time worrying about writing a custom event listener for each new element you add.
For a long time now, web developers have needed to store data on DOM elements. One of the most common methods was to add data as class names. Purists, like me, always felt wrong doing this, because that is not the place for data. An alternative way was to add custom attributes to the elements of interest. This practice lead to invalid markup because custom attributes were not supported by the specification. So, you ended up sacrificing validation in order to achieve your goal. This situation was very frustrating. Fortunately, HTML5 fixed it. In fact, HTML5 not only introduced the possibility of adding custom attributes via data attributes, but also exposed an API, called the dataset API, to work with them. In this article, we’ll discover how this API works and what it can do for us.
What is the Dataset API?
Among all the new elements (such as article
, section
, header
, and footer
) and the new APIs (such as High Resolution Time, User Timing, getUserMedia, and Page Visility), HTML5 also introduced data attributes and the dataset API. Before delving into our discussion of the dataset API, I want to give you a quick refresher of what are data attributes.
Data attributes get their name from the data-
prefix. This also explains why sometimes they are referred as data-*
attributes. An example of an element using data attributes is shown below.
<span id="element" data-level="1" data-points="100" data-opponent="Dragon"></span>
The names you can choose aren’t limited to a single word. Names can also consist of multiple words, separated by hyphens (-
). So, let’s say that you want to change the opponent
attribute to final opponent
. You would write the element as shown in the following example.
<span id="element" data-level="1" data-points="100" data-final-opponent="Dragon"></span>
You should now have a clear idea of what data attributes are, so let’s start discussing the API. The dataset API gives us a simple way of dealing with data attributes. This API allows us to set, get, or even delete data attribute values. The dataset API exposes a DOM element attribute named dataset
, which contains a DOMStringMap
object. This object’s keys are the names of the data attributes without the data-
prefix. The corresponding values are those of data attributes. If the name of an attribute is made of multiple words separated by a hyphen, it’s converted to camelCase. Let’s look at the following example:
var obj = document.getElementById("element").dataset
The previous statement will the following object in the variable obj
.
{
level: "1",
points: "100",
finalOpponent: "Dragon"
}
Individual data attributes can be accessed using the setAttribute()
, getAttribute()
, and removeAttribute()
methods. However, the dataset API gives you a convenient and direct way to access custom data. If the API is not supported, you should retrieve all the attributes and then filter those not starting with data-
. And, while the dataset API is simpler, it is also slower than the previously mentioned methods, as proven by this JSperf. However, unless you’re accessing thousands of attributes per second, you won’t notice any difference.
Now that we’ve discussed the dataset API, it’s time to see how we can use it.
Setting Values
Imagine we want to add the attribute data-media
to our element, and set its value to song
. To perform this task, we can write the following code. Note that if the attribute was already defined, its value is overwritten.
document.getElementById("element").dataset.media = "song";
Getting Values
Creating attributes is completely useless if we can’t retrieve them. Let’s say that we want to print the value of the data-final-opponent
attribute to the console. The code to do so would like like this:
console.log(document.getElementById("element").dataset.finalOpponent);
// prints "Dragon"
Deleting Attributes
To delete a value, simply overwrite it using the empty string. However, to actually delete an attribute we can use the JavaScript delete
operator. An example which deletes the data-final-opponent
attribute is shown below.
delete document.getElementById("element").dataset.finalOpponent;
After executing the previous statement, attempting to retrieve the attribute’s value will yield undefined
.
Browser Compatibility
The dataset API is widely supported among desktop and mobile browsers, aside from Internet Explorer which only implements the API in IE11. In addition, there are some older mobile browsers that don’t support it, but generally speaking the support is excellent. For those browser that don’t support this API, a polyfill named HTML 5 dataset Support is available. If you don’t want to add a polyfill for such a simple API, you can use setAttribute()
, getAttribute()
, and removeAttribute()
(as previously mentioned).
Demo
Learning something new is great, but it’s even better if we can play with it. So, we’ll build a small demo that will allow us to see how the dataset API works. The general idea is to have an element on which we can get, set and delete data attributes. To see what’s going on and to keep an eye on the current state of the element, we’ll have a small window where we’ll log the changes we made. In addition, we’ll have an area showing the raw HTML code of the element representing its current state.
In order to play with its data attributes, we need two input boxes: key and value. The former allows us to set the name of attribute we want to store, while the latter is where we’ll write the value of the attribute. Because we want to allow for three different actions (get, set, and delete), we’ll also need three buttons to which we’ll add handlers. As always, we’ll also test for browser support, and if the test fails, we’ll show the message “API not supported.”
Before showing you the demo code, there are two considerations I want to share with you. The demo assumes that you’ve read the whole article. Therefore, you’re aware that to perform an action on a data attribute named with more than one word, you have to convert the name to camelCase. If you want to change this behavior and be able to write “final-opponent” instead of “finalOpponent”, I’ve written two utility functions just for you. To use these functions, you need to add them to the demo and change the code so that you call them inside the handlers before performing the action. The source code of these functions is listed below.
function hyphenToCamelCase(string) {
return string.replace(/-([a-z])/g, function(string) {
return string[1].toUpperCase();
});
}
function camelCaseToHyphen(string) {
return string.replace(/([A-Z])/g, function(string) {
return '-' + string.toLowerCase();
});
}
The second thing to keep in mind is that so far we have accessed the data attributes using the dot operator because we knew its name ahead of time. In the demo we don’t have this information, so to access the properties of the dataset
, we’ll use the equivalent square bracket notation.
Now, it’s time to show you the source code. As usual, a live demo of the code is available here.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Dataset API Demo</title>
<style>
body
{
max-width: 500px;
margin: 2em auto;
font-size: 20px;
}
h1
{
text-align: center;
}
.hidden
{
display: none;
}
#log
{
height: 200px;
width: 100%;
overflow-y: scroll;
border: 1px solid #333333;
line-height: 1.3em;
}
.buttons-demo-wrapper
{
text-align: center;
}
.button-demo
{
padding: 0.5em;
margin: 1em;
}
.author
{
display: block;
margin-top: 1em;
}
</style>
</head>
<body>
<h1>Dataset API</h1>
<h3>Live sample element</h3>
<div id="showcase">
<span id="play-element" class="hidden" data-level="1" data-points="100" data-final-opponent="Dragon"></span>
</div>
<h3>Play area</h3>
<div>
<label for="key">Key:</label>
<input type="text" id="key"></input>
<label for="value">Value:</label>
<input type="text" id="value"></input>
<div class="buttons-demo-wrapper">
<button id="set-data" class="button-demo">Set data</button>
<button id="get-data" class="button-demo">Get data</button>
<button id="delete-data" class="button-demo">Delete data</button>
</div>
</div>
<span id="d-unsupported" class="hidden">API not supported</span>
<h3>Log</h3>
<div id="log"></div>
<button id="clear-log" class="button-demo">Clear log</button>
<span id="play-element" class="hidden" data-level="1" data-points="100" data-final-opponent="Dragon"></span>
<script>
if (!"dataset" in document.createElement("span")) {
document.getElementById("d-unsupported").classList.remove("hidden");
["set-data", "get-data", "delete-data"].forEach(function(elementId, index) {
document.getElementById(elementId).setAttribute("disabled", "disabled");
});
} else {
var playElement = document.getElementById("play-element");
var key = document.getElementById("key");
var value = document.getElementById("value");
var log = document.getElementById("log");
var showcase = document.getElementById("showcase");
document.getElementById("clear-log").addEventListener("click", function() {
log.innerHTML = "";
});
document.getElementById("set-data").addEventListener("click", function() {
if (key.value.indexOf("-") !== -1) {
log.innerHTML = "Warning! Hyphen not allowed. Use camelCase instead.n" + log.innerHTML;
} else {
playElement.dataset[key.value] = value.value;
showcase.textContent = playElement.outerHTML;
log.innerHTML = "Set data-" + key.value + " attribute to '" + value.value + "'<br />" + log.innerHTML;
}
});
document.getElementById("get-data").addEventListener("click", function() {
if (key.value.indexOf("-") !== -1) {
log.innerHTML = "Warning! Hyphen not allowed. Use camelCase instead.<br />" + log.innerHTML;
} else {
log.innerHTML = "Get data-" + key.value + " attribute. Value: '" + playElement.dataset[key.value] + "'<br />" + log.innerHTML;
}
});
document.getElementById("delete-data").addEventListener("click", function() {
if (key.value.indexOf("-") !== -1) {
log.innerHTML = "Warning! Hyphen not allowed. Use camelCase instead.<br />" + log.innerHTML;
} else {
delete playElement.dataset[key.value];
showcase.textContent = playElement.outerHTML;
log.innerHTML = "Deleted data-" + key.value + " attribute<br />" + log.innerHTML;
}
});
}
</script>
</body>
</html>
Conclusions
In this article, we’ve discussed the dataset API and how it can help us to store custom attributes on DOM elements. As we’ve seen, the API is very easy to use. In addition, it’s also widely supported among desktop and mobile browsers. You can start using it right away in your next project. In case you have any doubts, I encourage you to play with the provided demo or post a question.