- How to Get Values of Custom Data Attributes in JavaScript
- HTML Data Attribute Syntax
- Get Data Attributes with dataset Property in JavaScript
- Get Data Attributes with getAttribute Method in JavaScript
- Real-World Example of Data Attributes
- Conclusion
- Element: getAttribute() method
- Syntax
- Parameters
- Return value
- Examples
- Description
- Lower casing
- Non-existing attributes
- Retrieving nonce values
- Specifications
- Browser compatibility
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- .get Attribute ( )
- Как пишется
- Как понять
How to Get Values of Custom Data Attributes in JavaScript
Custom data attributes are a useful way to store extra information about an HTML element. You can easily get the data attribute value in JavaScript.
To get the values of custom data attributes in JavaScript, you can use the dataset property. This property allows you to access data attributes as properties of the element, using camelCase syntax. Simply reference the property with the same name as the data attribute, but without the data- prefix.
In this tutorial, we’ll discuss 2 ways to get the values of custom data attributes in JavaScript. We’ll start by looking at dataset property, which allows you to access data attributes as properties of the element.
Then, we’ll explore the getAttribute method to access the attribute value. But to understand them properly, you must know the HTML data attribute syntax.
HTML Data Attribute Syntax
In HTML, you can create a custom data attribute by using the data-* syntax, here * represents the name of the attribute you want to create. You are allowed to create any attribute you want with this syntax, as long as it starts with the prefix data- .
In this element, I have added 2 custom attributes first-name and last-name with some values. Whatever you use after data- will be the name of your data attribute. Let’s see how we can access those values with JavaScript.
Get Data Attributes with dataset Property in JavaScript
The dataset property is an object that allows you to access data attributes as properties of the element. It uses camelCase syntax, so the name you use for your data attribute will be converted to camelCase while accessing through the dataset property.
const user = document.getElementById('user') console.log(user.dataset.firstName) // John console.log(user.dataset.lastName) // Smith
For example, I am selecting the HTML element with the ID user and storing it to the user constant. Now I can access the dataset property on this element.
In this case, the dataset property will contain all the custom data attributes that this element has. You have to access the data-first-name and data-last-name attributes as user.dataset.firstName and user.dataset.lastName respectively.
In this way, you can get these attribute values in your JavaScript code.
Get Data Attributes with getAttribute Method in JavaScript
You can also use getAttribute() method to access data attribute values. For using the dataset property, you had to convert the attribute names to camelCase. But in this case, you have to pass the full name as a string to this method.
const user = document.getElementById('user') const firstName = user.getAttribute('data-first-name') console.log(firstName) // John const lastName = user.getAttribute('data-last-name') console.log(lastName) // Smith
Here, I am calling the getAttribute() method on the user element. I am passing the full attribute name to this method as its argument. It is important to note that the name will also include the data- prefix.
Then this method will return the value of that data attribute. If we pass an attribute name that doesn’t exist on that element, it will return null as the value.
Real-World Example of Data Attributes
You have seen how to access values from data attributes using JavaScript. Now let’s see a useful example to understand how we can use it in our code.
const link = document.getElementById('link') link.addEventListener('click', (e) => < e.preventDefault() if (confirm(link.dataset.confirm)) < console.log(link.dataset.itemId) // Send an AJAX request to the server to delete the item with the specified ID >>)
In this example, I have a link. When a user clicks that link, it will send an Ajax request to the server to delete an item. I am listening to the click event on this link.
The link has two data attributes: data-confirm , which contains a message to display to the user before deleting the item, and data-item-id , which contains the ID of that item.
When a user clicks the link, we use the dataset property to get the values of these attributes. After getting the confirmation, we can send the request to the server with the item ID.
This is just one simple example of using data attributes in a JavaScript application. But there are many other ways you can use them, depending on your specific needs.
Conclusion
Between these 2 ways, I like to use the dataset property in JavaScript. Because it is very easy to use and returns the value of the data attribute as the appropriate JavaScript type.
For example, if the value of the attribute is a string, the dataset property will return a string. If the value of the attribute is a boolean, the dataset property will return a boolean. The getAttribute method, on the other hand, always returns the value of the attribute as a string.
But it’s up to you which one you want to use to get data attribute values with JavaScript in your project.
Element: getAttribute() method
The getAttribute() method of the Element interface returns the value of a specified attribute on the element.
If the given attribute does not exist, the value returned will either be null or «» (the empty string); see Non-existing attributes for details.
Syntax
getAttribute(attributeName)
Parameters
Return value
A string containing the value of attributeName .
Examples
// in a console const div1 = document.getElementById("div1"); //=>Hi Champ!const exampleAttr = div1.getAttribute("id"); //=> "div1" const align = div1.getAttribute("align"); //=> null
Description
Lower casing
When called on an HTML element in a DOM flagged as an HTML document, getAttribute() lower-cases its argument before proceeding.
Non-existing attributes
All modern web browsers return null when the specified attribute does not exist on the specified element.
Retrieving nonce values
For security reasons, CSP nonces from non-script sources, such as CSS selectors, and .getAttribute(«nonce») calls are hidden.
let nonce = script.getAttribute("nonce"); // returns empty string
Instead of retrieving the nonce from the content attribute, use the nonce property:
Specifications
Browser compatibility
BCD tables only load in the browser
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
.get Attribute ( )
Метод get Attribute ( ) позволяет получить значение указанного атрибута у HTML-элемента. Если атрибута нет, то метод вернёт null .
Как пишется
Скопировать ссылку «Как пишется» Скопировано
get Attribute ( ) принимает один аргумент – строку с именем атрибута. В ответ метод возвращает значение атрибута в виде строки или null , если атрибута нет на элементе.
script type="application/json" id="hydration"> script>
const scriptElement = document.querySelector('script') console.log(scriptElement.getAttribute('type'))// 'application/json'console.log(scriptElement.getAttribute('id'))// 'hydration'console.log(scriptElement.getAttribute('class'))// null
const scriptElement = document.querySelector('script') console.log(scriptElement.getAttribute('type')) // 'application/json' console.log(scriptElement.getAttribute('id')) // 'hydration' console.log(scriptElement.getAttribute('class')) // null
Как понять
Скопировать ссылку «Как понять» Скопировано
Существует множество стандартных HTML-атрибутов, и разработчики могут задавать элементу свои собственные атрибуты. Метод get Attribute ( ) является универсальным способом прочитать значение любого атрибута.
Не все атрибуты имеет смысл считывать с помощью get Attribute ( ) . Например, атрибут hidden лучше читать из поля hidden DOM-элемента, а дата-атрибуты — из поля dataset .
Сравним два варианта получения значения атрибута. Возьмём элемент и считаем его атрибуты:
Ошибка!div data-color="red" hidden>Ошибка!div>
const element = document.querySelector('div') console.log(element.hidden)// trueconsole.log(element.getAttribute('hidden'))// "" – пустая строка, т.к строкового значения у атрибута нет console.log(element.dataset.color)// "red"console.log(element.getAttribute('data-color'))// "red"
const element = document.querySelector('div') console.log(element.hidden) // true console.log(element.getAttribute('hidden')) // "" – пустая строка, т.к строкового значения у атрибута нет console.log(element.dataset.color) // "red" console.log(element.getAttribute('data-color')) // "red"