πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Data Attributes

Web Foundations🟒 Free Lesson

Advertisement

Data Attributes

Custom data storage, JavaScript hooks, and component communication.

Overview

Data attributes store custom data on HTML elements.

Key Concepts

  • data- Attributes* β€” Custom data storage
  • JavaScript Access β€” dataset property
  • CSS Selectors β€” Attribute selectors
  • Event Delegation β€” Handle dynamic elements
  • Component Communication β€” Pass data between components

Code Examples

<div id="users" data-api-url="/api/users" data-page-size="10">
</div>

<ul id="productList" data-product-ids="1,2,3">
  <li data-product-id="1" data-price="29.99" data-category="electronics">
    Product 1
  </li>
  <li data-product-id="2" data-price="49.99" data-category="clothing">
    Product 2
  </li>
</ul>

<script>
// Access data attributes
const usersDiv = document.getElementById('users');
console.log(usersDiv.dataset.apiUrl); // "/api/users"
console.log(usersDiv.dataset.pageSize); // "10" (always string)

// Modify data attributes
usersDiv.dataset.pageNumber = '2';
usersDiv.dataset.pageSize = '20';

// Event delegation with data attributes
document.getElementById('productList').addEventListener('click', (e) => {
  const productItem = e.target.closest('[data-product-id]');
  
  if (productItem) {
    const { productId, price, category } = productItem.dataset;
    console.log(`Product: ${productId}, Price: $${price}, Category: ${category}`);
  }
});

// CSS attribute selectors
document.head.insertAdjacentHTML('beforeend', `
  <style>
    [data-category="electronics"] {
      border-left: 3px solid #007bff;
    }
    
    [data-price]::after {
      content: attr(data-price);
      font-weight: bold;
      color: #28a745;
    }
    
    [data-active="true"] {
      background: #d4edda;
    }
  </style>
`);

// Fetch data based on data attributes
async function loadDataFromElement(element) {
  const url = element.dataset.apiUrl;
  const pageSize = parseInt(element.dataset.pageSize) || 10;
  const pageNumber = parseInt(element.dataset.pageNumber) || 1;
  
  const response = await fetch(`${url}?page=${pageNumber}&size=${pageSize}`);
  return response.json();
}
</script>

Practice

Build a data-driven component using data attributes for configuration.

⭐

Premium Content

Data Attributes

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement