Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to declare a custom attribute in HTML?
In this article, we will discuss how to declare a custom attribute in HTML. Custom attributes are useful when you want to store additional information that is not part of standard HTML attributes. They provide flexibility and customization in HTML, making your code more maintainable and functional.
Approaches
We have two different approaches to declaring a custom attribute in HTML
Using the data- prefix Standard HTML5 approach for custom attributes
Using custom attributes Non-standard approach with custom naming
Syntax
Following is the syntax for data- attributes
<tag data-attribute-name="value">Content</tag>
Following is the syntax for custom attributes
<tag custom-attribute="value">Content</tag>
Using the data- Prefix Method
The data- prefix is the standard HTML5 approach for creating custom attributes. Any attribute that starts with data- is considered a valid custom attribute. This method ensures HTML validation compliance and provides built-in JavaScript support through the dataset property.
The data- attributes can be easily accessed in JavaScript using element.dataset.attributeName or element.getAttribute("data-attribute-name"). In CSS, they can be targeted using attribute selectors like [data-attribute="value"].
Example
Following example demonstrates declaring custom attributes using the data- prefix in an employee table
<!DOCTYPE html>
<html>
<head>
<title>Employee Table with Data Attributes</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
h1 { color: #2c3e50; }
table { border-collapse: collapse; width: 100%; margin-top: 20px; }
th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }
th { background-color: #3498db; color: white; }
tr:nth-child(even) { background-color: #f8f9fa; }
tr:hover { background-color: #e8f4f8; }
.highlight { background-color: #fff3cd !important; }
</style>
</head>
<body>
<h1>Employee Information System</h1>
<table>
<thead>
<tr>
<th>Employee ID</th>
<th>Name</th>
<th>Department</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr data-empid="001" data-dept="IT" data-salary="75000" data-level="senior">
<td>001</td>
<td>Taylor</td>
<td>IT</td>
<td>$75,000</td>
</tr>
<tr data-empid="002" data-dept="HR" data-salary="60000" data-level="junior">
<td>002</td>
<td>John</td>
<td>HR</td>
<td>$60,000</td>
</tr>
<tr data-empid="003" data-dept="Finance" data-salary="80000" data-level="senior">
<td>003</td>
<td>Sarah</td>
<td>Finance</td>
<td>$80,000</td>
</tr>
</tbody>
</table>
<button onclick="highlightSenior()">Highlight Senior Employees</button>
<script>
// Access data attributes using dataset property
const rows = document.querySelectorAll("tr[data-empid]");
rows.forEach(row => {
const empid = row.dataset.empid;
const dept = row.dataset.dept;
const salary = row.dataset.salary;
const level = row.dataset.level;
console.log(`Employee ID: ${empid}, Department: ${dept}, Salary: $${salary}, Level: ${level}`);
});
function highlightSenior() {
const seniorRows = document.querySelectorAll("tr[data-level='senior']");
seniorRows.forEach(row => {
row.classList.toggle('highlight');
});
}
</script>
</body>
</html>
The output displays an employee table with custom data attributes. JavaScript accesses these attributes using the dataset property, and the button highlights senior-level employees
Employee Information System Employee ID Name Department Salary 001 Taylor IT $75,000 002 John HR $60,000 003 Sarah Finance $80,000 [Highlight Senior Employees] Console output: Employee ID: 001, Department: IT, Salary: $75000, Level: senior Employee ID: 002, Department: HR, Salary: $60000, Level: junior Employee ID: 003, Department: Finance, Salary: $80000, Level: senior
Using Custom Attributes
Custom attributes without the data- prefix are non-standard but still functional. While they work in browsers, they do not pass HTML validation and are not recommended for production use. This approach provides naming flexibility but lacks the built-in JavaScript dataset support.
Custom attributes must be accessed using getAttribute() and setAttribute() methods in JavaScript. They can still be targeted in CSS using attribute selectors.
Example
Following example demonstrates custom attributes without the data- prefix
<!DOCTYPE html>
<html>
<head>
<title>Custom Attribute Example</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
[theme="dark"] { background-color: #2c3e50; color: white; padding: 15px; }
[priority="high"] { border-left: 4px solid #e74c3c; padding-left: 10px; }
[status="active"] { color: #27ae60; font-weight: bold; }
</style>
</head>
<body>
<h1 theme="dark">TutorialsPoint</h1>
<p priority="high">This is a high-priority message!</p>
<p status="active">System is currently active</p>
<button onclick="toggleTheme()">Toggle Theme</button>
<script>
// Access custom attributes using getAttribute()
const header = document.querySelector("[theme='dark']");
const highPriority = document.querySelector("[priority='high']");
const statusText = document.querySelector("[status='active']");
console.log(`Header theme: ${header.getAttribute('theme')}`);
console.log(`Priority level: ${highPriority.getAttribute('priority')}`);
console.log(`Status: ${statusText.getAttribute('status')}`);
function toggleTheme() {
const currentTheme = header.getAttribute('theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
header.setAttribute('theme', newTheme);
}
</script>
</body>
</html>
The output shows elements styled based on custom attributes. The header has a dark theme, the high-priority message has a red border, and the status text appears in green
TutorialsPoint (dark background, white text) This is a high-priority message! (red left border) System is currently active (green, bold text) [Toggle Theme]
Example Product Catalog with Custom Attributes
Following example shows a practical use case with product information
<!DOCTYPE html>
<html>
<head>
<title>Product Catalog</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
.product { border: 1px solid #ddd; margin: 10px 0; padding: 15px; border-radius: 5px; }
.product[data-category="electronics"] { border-color: #3498db; }
.product[data-category="clothing"] { border-color: #e74c3c; }
.product[data-stock="low"] { background-color: #fff3cd; }
.product[data-featured="true"] { box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
</style>
</head>
<body>
<h1>Product Catalog</h1>
<div class="product" data-id="p001" data-category="electronics" data-price="299" data-stock="high" data-featured="true">
<h3>Smartphone</h3>
<p>Latest model with advanced features</p>
<p>Price: $299</p>
</div>
<div class="product" data-id="p002" data-category="clothing" data-price="49" data-stock="low" data-featured="false">
<h3>Cotton T-Shirt</h3>
<p>Comfortable cotton material</p>
<p>Price: $49</p>
</div>
<button onclick="showFeatured()">Show Featured Products</button>
<script>
function showFeatured() {
const featured = document.querySelectorAll(".product[data-featured='true']");
const result = [];
featured.forEach(product => {
const id = product.dataset.id;
const category = product.dataset.category;
const price = product.dataset.price;
result.push(`Product ${id}: ${category} - $${price}`);
});
alert("Featured Products:<br>" + result.join("<br>"));
}
</script>
</body>
</html>
This example demonstrates how data attributes can store structured product information and be used for filtering and styling.
Comparison Between Methods
Following table compares the two approaches for creating custom attributes
| data- Prefix Method | Custom Attributes Method |
|---|
