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
Accessing Data in JavaScript
JavaScriptRead-only
1
Accessing with getAttribute
JavaScriptRead-only
1
Setting Data Attributes
JavaScriptRead-only
1
Using Data Attributes in CSS
CSSRead-only
1
Example Use Case
HTMLRead-only
1
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.