Attributes
Attributes add extra information to an element: where a link goes, which image to show, how a form field behaves. They're written inside the opening tag as name="value" pairs, and some apply to every element.
Attribute syntax
<a href="https://example.com" title="Visit the example site">Example</a>
- Attributes go in the opening tag, after the element name, separated by spaces.
- The value goes in quotes. Double quotes are conventional; single quotes also work.
- Attribute order doesn't matter.
- Names are case-insensitive but written in lowercase by convention.
Common attributes by element
| Attribute | Used on | Purpose |
|---|---|---|
href | <a>, <link> | Destination URL |
src | <img>, <script>, <video>, <iframe> | Source file |
alt | <img> | Text alternative for images |
width, height | Images, video, canvas | Intrinsic size in pixels |
type, name, value, placeholder | Form controls | Field behaviour and data |
Global attributes
These can be used on any element:
| Attribute | Purpose |
|---|---|
id | A unique identifier for one element on the page (lesson 23) |
class | One or more space-separated class names for styling and scripting |
style | Inline CSS (use sparingly — lesson 36) |
title | Extra advisory text, often shown as a tooltip |
lang | Language of the element's content |
hidden | Hides the element |
tabindex | Controls keyboard focus order |
data-* | Custom data for scripts |
contenteditable, draggable, translate, dir | Editing, drag and drop, translation, text direction |
Boolean attributes
Some attributes are on or off. Their presence alone means "true" — the value doesn't matter:
Writing disabled="false" does not enable the element — the attribute is still present. To turn a boolean attribute off, remove it entirely.
Custom data attributes
Any attribute starting with data- is valid and reserved for your own use. Scripts read them via the dataset property:
<button type="button" data-product-id="482" data-price="19.99">Add to cart</button>
In JavaScript, button.dataset.productId is "482". CSS can target them too: [data-price]. They're perfect for attaching IDs and settings to elements without inventing non-standard attributes.
Quoting rules
Quotes are technically optional when a value has no spaces or special characters, but always quoting avoids bugs:
<img src="photo.jpg" alt="My dog"> <p title='He said "woof"'>Use single quotes when the value contains double quotes.</p> <p title="He said "woof"">Or escape them with &quot;.</p>
Try it yourself
Experiment: change the link's href, add a title, or remove the disabled attribute from the button.