1. Home
  2. Coding Hub
  3. Coding Notes
  4. Html
  5. Data Attributes
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
02Hrs
38Mins
06Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Html
  5. Data Attributes

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
02Hrs
38Mins
06Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
HTML IntroductionDOM ParsingDocument StructureMetadata & <head>Viewport SetupLinks & FaviconsScript Loading
Heading HierarchyText SemanticsBlock vs InlineHyperlinks & AnchorsHTML ListsSemantic LayoutSectioning Elements
Image OptimizationResponsive <picture>Audio & VideoMedia <track>Inline SVG<iframe> Sandboxing
Table BasicsTable SemanticsSpanning & Captions
Form ArchitectureText InputsSelection ControlsSpecialized InputsLabels & Fieldsets<datalist> AutocompleteNative ValidationForm Submission
<details> Accordions<dialog> ModalsPopover APIInvoker Commands<template> Tag
data-* AttributesWeb AccessibilityARIA EssentialsOpen Graph SEOResource Hints
HTML

data-* Attributes

Overview

Sometimes you need to store custom, application-specific data directly on an HTML element so your JavaScript or CSS can access it later. However, creating completely fake HTML attributes (like <div product-id="12">) is strictly invalid and breaks HTML parsing. HTML5 introduced data-* attributes as the official, standard way to embed custom data natively. These attributes are completely ignored by the browser's visual engine, but are effortlessly accessible via JavaScript's native dataset API.

Syntax

html
<!-- 
  We attach custom 'data-' attributes to hold information 
  that JavaScript will need when the user clicks the button.
-->
<button 
  class="add-to-cart" 
  data-product-id="99102" 
  data-price="49.99" 
  data-category="electronics"
>
  Add to Cart
</button>

<script>
  const btn = document.querySelector('.add-to-cart');
  
  // The 'dataset' object automatically strips the 'data-' prefix 
  // and converts kebab-case to camelCase!
  console.log(btn.dataset.productId); // "99102"
  console.log(btn.dataset.price);     // "49.99"
</script>

Common Pitfalls

  • Storing highly sensitive data (like data-user-password="1234") in data attributes. Data attributes are physically written into the HTML text payload, meaning anyone can right-click, 'Inspect Element', and see the data.
  • Using capital letters in the HTML attribute name (e.g., data-productId="12"). HTML attributes are strictly case-insensitive. You must use kebab-case (data-product-id), which JavaScript will automatically magically transform into camelCase (dataset.productId).

Interview Questions

How can you use data-* attributes directly inside your CSS?

You can use the attr() CSS function or attribute selectors. For example: .add-to-cart::after { content: attr(data-price); } will literally print the price into the UI using only CSS.

Real-World Example

Managing a Dark/Light theme toggle entirely via data attributes.

example
html
<!-- By setting a data attribute on the root HTML tag... -->
<html data-theme="dark">

<style>
  /* ...we can universally switch the color palette using CSS variables! */
  html[data-theme="dark"] {
    --bg-color: #000;
    --text-color: #fff;
  }
  html[data-theme="light"] {
    --bg-color: #fff;
    --text-color: #000;
  }
  body { background: var(--bg-color); color: var(--text-color); }
</style>
</html>

Check Your Knowledge

Test your understanding of data-* Attributes with these quick questions.

Question 1

If an element has `data-user-first-name="Kartik"`, how would you correctly access it via JavaScript?

Take HTML Quiz
Outline
HTML IntroductionDOM ParsingDocument StructureMetadata & <head>Viewport SetupLinks & FaviconsScript Loading
Heading HierarchyText SemanticsBlock vs InlineHyperlinks & AnchorsHTML ListsSemantic LayoutSectioning Elements
Image OptimizationResponsive <picture>Audio & VideoMedia <track>Inline SVG<iframe> Sandboxing
Table BasicsTable SemanticsSpanning & Captions
Form ArchitectureText InputsSelection ControlsSpecialized InputsLabels & Fieldsets<datalist> AutocompleteNative ValidationForm Submission
<details> Accordions<dialog> ModalsPopover APIInvoker Commands<template> Tag
data-* AttributesWeb AccessibilityARIA EssentialsOpen Graph SEOResource Hints
HTML

data-* Attributes

Overview

Sometimes you need to store custom, application-specific data directly on an HTML element so your JavaScript or CSS can access it later. However, creating completely fake HTML attributes (like <div product-id="12">) is strictly invalid and breaks HTML parsing. HTML5 introduced data-* attributes as the official, standard way to embed custom data natively. These attributes are completely ignored by the browser's visual engine, but are effortlessly accessible via JavaScript's native dataset API.

Syntax

html
<!-- 
  We attach custom 'data-' attributes to hold information 
  that JavaScript will need when the user clicks the button.
-->
<button 
  class="add-to-cart" 
  data-product-id="99102" 
  data-price="49.99" 
  data-category="electronics"
>
  Add to Cart
</button>

<script>
  const btn = document.querySelector('.add-to-cart');
  
  // The 'dataset' object automatically strips the 'data-' prefix 
  // and converts kebab-case to camelCase!
  console.log(btn.dataset.productId); // "99102"
  console.log(btn.dataset.price);     // "49.99"
</script>

Common Pitfalls

  • Storing highly sensitive data (like data-user-password="1234") in data attributes. Data attributes are physically written into the HTML text payload, meaning anyone can right-click, 'Inspect Element', and see the data.
  • Using capital letters in the HTML attribute name (e.g., data-productId="12"). HTML attributes are strictly case-insensitive. You must use kebab-case (data-product-id), which JavaScript will automatically magically transform into camelCase (dataset.productId).

Interview Questions

How can you use data-* attributes directly inside your CSS?

You can use the attr() CSS function or attribute selectors. For example: .add-to-cart::after { content: attr(data-price); } will literally print the price into the UI using only CSS.

Real-World Example

Managing a Dark/Light theme toggle entirely via data attributes.

example
html
<!-- By setting a data attribute on the root HTML tag... -->
<html data-theme="dark">

<style>
  /* ...we can universally switch the color palette using CSS variables! */
  html[data-theme="dark"] {
    --bg-color: #000;
    --text-color: #fff;
  }
  html[data-theme="light"] {
    --bg-color: #fff;
    --text-color: #000;
  }
  body { background: var(--bg-color); color: var(--text-color); }
</style>
</html>

Check Your Knowledge

Test your understanding of data-* Attributes with these quick questions.

Question 1

If an element has `data-user-first-name="Kartik"`, how would you correctly access it via JavaScript?

Take HTML Quiz

HTML coding notes for Indian students — 41 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in HTML

  1. HTML Introduction
  2. DOM Parsing
  3. Document Structure
  4. Metadata & <head>
  5. Viewport Setup
  6. Links & Favicons
  7. Script Loading
  8. Heading Hierarchy
  9. Text Semantics
  10. Block vs Inline
  11. Hyperlinks & Anchors
  12. HTML Lists
  13. Semantic Layout
  14. Sectioning Elements
  15. Image Optimization
  16. Responsive <picture>
  17. Audio & Video
  18. Media <track>
  19. Inline SVG
  20. <iframe> Sandboxing
  21. Table Basics
  22. Table Semantics
  23. Spanning & Captions
  24. Form Architecture
  25. Text Inputs
  26. Selection Controls
  27. Specialized Inputs
  28. Labels & Fieldsets
  29. <datalist> Autocomplete
  30. Native Validation
  31. Form Submission
  32. <details> Accordions
  33. <dialog> Modals
  34. Popover API
  35. Invoker Commands
  36. <template> Tag
  37. data-* Attributes
  38. Web Accessibility
  39. ARIA Essentials
  40. Open Graph SEO
  41. Resource Hints

Study next

  • All coding notes
  • HTML notes home
  • HTML certification quiz
  • Online compiler
  • Interview Q&A

HTML coding notes for Indian students — 41 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in HTML

  1. HTML Introduction
  2. DOM Parsing
  3. Document Structure
  4. Metadata & <head>
  5. Viewport Setup
  6. Links & Favicons
  7. Script Loading
  8. Heading Hierarchy
  9. Text Semantics
  10. Block vs Inline
  11. Hyperlinks & Anchors
  12. HTML Lists
  13. Semantic Layout
  14. Sectioning Elements
  15. Image Optimization
  16. Responsive <picture>
  17. Audio & Video
  18. Media <track>
  19. Inline SVG
  20. <iframe> Sandboxing
  21. Table Basics
  22. Table Semantics
  23. Spanning & Captions
  24. Form Architecture
  25. Text Inputs
  26. Selection Controls
  27. Specialized Inputs
  28. Labels & Fieldsets
  29. <datalist> Autocomplete
  30. Native Validation
  31. Form Submission
  32. <details> Accordions
  33. <dialog> Modals
  34. Popover API
  35. Invoker Commands
  36. <template> Tag
  37. data-* Attributes
  38. Web Accessibility
  39. ARIA Essentials
  40. Open Graph SEO
  41. Resource Hints

Study next

  • All coding notes
  • HTML notes home
  • HTML certification quiz
  • Online compiler
  • Interview Q&A