Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Custom Data Attributes – `data-*` | HTML Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. HTML Course

Lesson 49 of 55

·HTML

Custom Data Attributes – `data-*`

9 min

Course progress89%

What you'll learn

Keep these ideas in mind as you work through the lesson.

5 points
  • Syntax and access via `element.dataset`
  • Naming conventions and camelCase conversion
  • Best practices for small payloads and type conversion
  • When to prefer `data-*` versus other data‑passing mechanisms (JSON script blocks, storage)
  • Common use‑cases in UI widgets and analytics

Custom Data Attributes – data-*

data-* attributes let you embed custom data in HTML without affecting semantics.

<button class='add-to-cart' data-product-id='12345' data-price='19.99'>Add to Cart</button>

<script>
  document.querySelector('.add-to-cart').addEventListener('click', e => {
    const btn = e.currentTarget;
    const id = btn.dataset.productId;
    const price = btn.dataset.price;
    console.log(`Product ${id} costs $${price}`);
  });
</script>

Rules

  • Attribute name must start with data- and may contain letters, digits, hyphens, periods, and underscores.
  • Access via element.dataset; hyphens become camelCase (data-user-id → element.dataset.userId).
  • Values are always strings; convert to numbers or booleans as needed.

When to use

  • Passing configuration or identifiers to JavaScript.
  • Storing UI state that doesn’t affect rendering.
  • For small, JSON‑like configuration objects (keep payloads tiny).

Best practices

  • Keep data attributes small – avoid large blobs of JSON.
  • Use meaningful names (data-category, data-index).
  • For large structured data, consider a <script type='application/json'> block or client‑side storage.

Quick checklist for data-*

  1. Attribute name starts with data-? ✅
  2. Accessed via element.dataset in JavaScript? ✅
  3. Values kept small and type‑converted as needed? ✅
  4. No critical UI logic relies solely on data attributes? ✅
  5. Fallback behaviour defined if JavaScript is disabled? ✅

Tip: When you need to expose a configuration object to many components, use a <script type='application/json' id='config'> element and parse it once.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from HTML CourseBrowse activities
Previous lessonThe `<time>` Element – Machine‑readable Dates & TimesContinue to lesson 50SEO Advanced – Breadcrumbs with `nav[aria-label="breadcrumb"]` and JSON‑LDBack to HTML Course curriculum