What Are Attributes?
An attribute lives inside the opening tag, separated from the element name and from other attributes by a space. The value is wrapped in double quotes.
<!-- Syntax: element name, then space, then name="value" -->
<a href="https://ylearner.org" target="_blank">ylearner</a>
<!-- ^ element ^ attribute 1 ^ attribute 2 -->
<img src="/assets/logo.png" alt="ylearner logo" width="120">
<input type="email" id="email" name="email" required placeholder="you@example.com">
'), double quotes ("), or even no quotes (if the value has no spaces). Double quotes are the universal convention β always use them for consistency and compatibility.
Global Attributes Reference
These attributes can be added to any HTML element:
| Attribute | Purpose | Example |
|---|---|---|
id | Unique identifier β one per page | id="main-nav" |
class | Reusable CSS/JS label(s) | class="btn btn-primary" |
style | Inline CSS styles | style="color: red;" |
title | Tooltip text on hover | title="Click to expand" |
lang | Language of element's content | lang="fr" |
dir | Text direction: ltr or rtl | dir="rtl" |
hidden | Hides element (boolean) | hidden |
tabindex | Tab order for keyboard navigation | tabindex="0" |
contenteditable | Makes element editable in browser | contenteditable="true" |
draggable | Enables HTML drag-and-drop | draggable="true" |
spellcheck | Enable/disable spell checking | spellcheck="false" |
translate | Hint to translation tools | translate="no" |
aria-* | ARIA accessibility attributes | aria-label="Close" |
data-* | Custom data storage | data-user-id="42" |
The id Attribute
The id attribute assigns a unique identifier to an element. No two elements on the same page should share an id.
Three key uses of id:
- Fragment links β link directly to a section of the page with
href="#section-name" - CSS targeting β target with the
#idselector - JavaScript β retrieve with
document.getElementById('id')
<!-- Fragment link: clicking this jumps to the section below -->
<a href="#about">Jump to About section</a>
<!-- Target section with id -->
<section id="about">
<h2>About ylearner</h2>
<p>Free coding tutorials for everyone.</p>
</section>
<!-- CSS targeting -->
<style>
#about { background: #f0f4ff; padding: 2rem; }
</style>
<!-- JavaScript targeting -->
<script>
const about = document.getElementById('about');
about.style.border = '2px solid blue';
</script>
The class Attribute
The class attribute assigns one or more reusable labels to an element. Multiple elements can share the same class, and a single element can have multiple classes (space-separated).
<!-- Multiple classes on one element -->
<button class="btn btn-primary btn-large">Start Learning</button>
<!-- Multiple elements sharing the same class -->
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card card--featured">Featured Card</div>
<!-- CSS targeting all cards -->
<style>
.card { border: 1px solid #dee2e6; padding: 1rem; border-radius: 8px; }
.card--featured { border-color: #0d6efd; }
</style>
<!-- JavaScript targeting all cards -->
<script>
document.querySelectorAll('.card').forEach(card => {
card.addEventListener('click', () => card.classList.toggle('card--active'));
});
</script>
The style Attribute β Inline CSS
The style attribute applies CSS directly to a single element. Use it sparingly β inline styles have very high specificity and are hard to override. They also mix presentation with structure, which makes maintenance harder.
<!-- Acceptable: one-off dynamic styles set by JavaScript -->
<p id="status" style="color: green; font-weight: bold;">Online</p>
<!-- Better: use a class instead -->
<p id="status" class="status status--online">Online</p>
<!-- Inline styles are fine for email HTML where external CSS won't work -->
<td style="padding: 12px; background-color: #f8f9fa;">Email cell</td>
style attribute for dynamic values set by JavaScript, or for HTML email templates where external stylesheets are unreliable.
The title Attribute
The title attribute adds a tooltip that appears when the user hovers over the element. It's also read by some screen readers.
<!-- Tooltip on a link -->
<a href="/html/core-elements/tables.html" title="Learn to build data tables in HTML">
HTML Tables
</a>
<!-- Tooltip on an abbreviation -->
<p>Written in <abbr title="HyperText Markup Language">HTML</abbr>.</p>
<!-- Tooltip on an image -->
<img src="chart.png" alt="Bar chart of course completion rates" title="Data from JanβJune 2026">
title tooltip is not accessible on touch screens and is not always announced by screen readers. Don't rely on it to convey critical information β use visible text or aria-label/aria-describedby for essential content.
Data Attributes β data-*
Custom data attributes let you store extra information on HTML elements without affecting layout or semantics. They follow the pattern data- followed by any name you choose.
<!-- Store data on elements for JavaScript to read -->
<button class="enroll-btn" data-course-id="html-101" data-price="0">
Enrol Free
</button>
<ul class="lesson-list">
<li data-lesson-id="1" data-duration="5">Introduction to HTML</li>
<li data-lesson-id="2" data-duration="8">HTML Document Structure</li>
<li data-lesson-id="3" data-duration="10">Block vs Inline Elements</li>
</ul>
// Read data attributes with dataset
const btn = document.querySelector('.enroll-btn');
console.log(btn.dataset.courseId); // "html-101"
console.log(btn.dataset.price); // "0"
// dataset uses camelCase for hyphenated attribute names
// data-course-id β dataset.courseId
// data-lesson-id β dataset.lessonId
// Iterate over lessons and total their duration
let totalMinutes = 0;
document.querySelectorAll('[data-duration]').forEach(item => {
totalMinutes += parseInt(item.dataset.duration, 10);
});
console.log(`Total: ${totalMinutes} minutes`); // "Total: 23 minutes"
Boolean Attributes
Some attributes don't need a value β their presence alone activates the feature. These are called boolean attributes. The value (if written) must be either the attribute name itself or an empty string.
<!-- Boolean attributes: presence = true, absence = false -->
<!-- Disable a button -->
<button disabled>Submit</button>
<!-- Pre-check a checkbox -->
<input type="checkbox" checked>
<!-- Mark an input as required -->
<input type="email" required>
<!-- Make an input read-only -->
<input type="text" value="gmostafa1210@gmail.com" readonly>
<!-- Allow multiple file selection -->
<input type="file" multiple>
<!-- Autoplay a video (muted required in most browsers) -->
<video src="intro.mp4" autoplay muted loop></video>
<!-- Hide an element -->
<div hidden>This won't render on screen</div>
<!-- All of these are equivalent for boolean attributes: -->
<input required>
<input required="">
<input required="required">
Attributes: Global, Boolean, and Custom data-*
Attributes configure elements. Some are global (work on any element), some are boolean (presence alone means true), and data-* lets you attach your own custom data.
| Kind | Example | Note |
|---|---|---|
| Global | id, class, title, style, hidden | valid on every element |
| Boolean | disabled, checked, required, readonly | no value needed |
| Custom | data-user-id="42" | your own data, read via JS |
<!-- boolean: presence = true. There is no disabled="false"! -->
<button disabled>Can't click</button>
<!-- custom data, read in JS via dataset -->
<li data-user-id="42" data-role="admin">Ann</li>
li.dataset.userId; // "42" (data-user-id β camelCase userId)
li.dataset.role; // "admin"
Boolean gotcha: disabled="false" does not enable the element β any presence of the attribute means true. To turn it off, remove the attribute entirely. For custom data, always use the data- prefix (never invent bare attributes like userid) so your HTML stays valid and readable via the .dataset API. Quote attribute values by habit β required whenever the value has spaces.
ποΈ Practical Exercise
- Add an
idattribute to a heading. - Add a
classattribute to a paragraph. - Give a link both
hrefandtitleattributes. - Add a boolean attribute like
disabledto a button. - Use a custom
data-*attribute (e.g.data-role="admin") on a div.
π₯ Challenge Exercise
Create a button with at least four attributes: an id, a class, a type, and a disabled boolean attribute. Then add a data-tooltip custom attribute. Inspect the element in DevTools and confirm every attribute appears in its attribute list.
π Summary
- Attributes are
name="value"pairs inside opening tags. Always use double quotes around values. - Global attributes work on any element:
id,class,style,title,lang,dir,hidden,tabindex,contenteditable. idβ unique per page; used for fragment links, CSS#selector, andgetElementById().classβ reusable; multiple per element; targeted by CSS.selectorandquerySelectorAll().styleβ inline CSS; use sparingly; prefer external/class-based CSS.data-*β custom data storage for JavaScript; accessed viaelement.dataset.attributeName.- Boolean attributes (
disabled,checked,required,readonly,hidden) β presence alone activates them; no value needed.
Interview Questions
- What is the general syntax of an HTML attribute?
- What is the difference between an
idand aclassattribute? - What is a boolean attribute? Give an example.
- What are
data-*attributes used for? - Should attribute values be quoted, and why?
Related Topics
FAQ
In HTML5 (not XML/XHTML), attribute names are case-insensitive β ID, Id, and id are all valid. However, the convention is always lowercase. Attribute values can be case-sensitive depending on the attribute β URL values are case-sensitive on case-sensitive servers, and CSS class names in HTML are case-sensitive when referenced from CSS or JavaScript.
Yes β use data-* attributes for custom data. Do not invent arbitrary attribute names like <div myattr="value"> β those are non-standard, may cause validation errors, and could conflict with future HTML attributes. Always prefix custom data with data-.
tabindex controls whether an element is focusable by keyboard (Tab key) and its position in the tab order. tabindex="0" adds the element to the natural tab order. tabindex="-1" makes it focusable by script only (useful for modal dialogs). Positive values (tabindex="1", tabindex="2", etc.) set an explicit order but are generally discouraged because they override the natural DOM order and are hard to maintain.
Not categorically β it depends on context. For dynamically calculated values in JavaScript, inline styles are perfectly appropriate. For email HTML templates, they are often the only reliable option. For regular web pages, prefer CSS classes for maintainability, separation of concerns, and ease of theming. A good rule of thumb: if the value never changes based on user interaction or data, it belongs in a stylesheet, not an inline style attribute.

