html
/

HTML Data Attributes: Custom Data Storage

Last Sync: Today

On this page

11
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

html

HTML Data Attributes: Custom Data Storage

What are Data Attributes?

HTML data attributes allow you to store custom data directly on HTML elements using the data-* format.

Basic Syntax

HTMLRead-only
1
<div data-user="john" data-id="123"></div>

Accessing Data in JavaScript

JavaScriptRead-only
1
const el = document.querySelector('div');
console.log(el.dataset.user); // john
console.log(el.dataset.id);   // 123

Accessing with getAttribute

JavaScriptRead-only
1
el.getAttribute('data-user');

Setting Data Attributes

JavaScriptRead-only
1
el.dataset.user = 'alice';
el.setAttribute('data-role', 'admin');

Using Data Attributes in CSS

CSSRead-only
1
[data-role="admin"] {
  background: #eee;
}

Example Use Case

HTMLRead-only
1
<button data-product-id="101">Add to Cart</button>

Naming Rules

  • Must start with data-
  • Use lowercase letters
  • Use hyphens for multiple words (data-user-id)
  • Avoid special characters

Best Practices

  • Use data attributes for storing small data only
  • Keep names meaningful and descriptive
  • Use dataset for easy access in JavaScript
  • Avoid storing sensitive information
  • Use for UI-related data only

Common Mistakes

  • Storing large or complex data
  • Using data attributes instead of proper state management
  • Incorrect naming (missing data- prefix)
  • Exposing sensitive data in HTML

Conclusion

HTML data attributes provide a simple way to store custom data in elements. They are useful for enhancing interactivity with JavaScript.

Try it yourself

<div data-name="John"></div>
<script>
const el = document.querySelector('div');
console.log(el.dataset.name);
</script>

Test Your Knowledge

Q1
of 3

What prefix is used for custom data?

A
custom-
B
data-
C
attr-
D
info-
Q2
of 3

How to access data-user in JS?

A
el.data.user
B
el.dataset.user
C
el.get.user
D
el.user
Q3
of 3

Can CSS target data attributes?

A
No
B
Yes
C
Only JS
D
Only inline

Frequently Asked Questions

What is data-* in HTML?

It is used to store custom data on HTML elements.

How to access data attributes in JS?

Using element.dataset or getAttribute.

Can data attributes be styled?

Yes, using CSS attribute selectors.

Previous

html noscript

Next

css introduction

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.