Question
In HTML, what rules apply to the id attribute value of an element? For example, what characters are allowed, what restrictions exist, and what naming practices are recommended when creating id values?
Short Answer
By the end of this page, you will understand what an HTML id is, what makes an id value valid, how it is used in CSS and JavaScript, why uniqueness matters, and which naming conventions make your markup easier to maintain.
Concept
An HTML id is a unique identifier for a single element on a page. It is commonly used for:
- linking to a specific element with a fragment like
#section-1 - selecting an element in CSS
- finding an element in JavaScript with
getElementById() - associating labels, inputs, and accessibility attributes
In modern HTML, the main rule is that an id value must be unique within the document and must not contain ASCII whitespace such as spaces, tabs, or line breaks.
For example:
<div id="header"></div>
<section id="product-list"></section>
<input id="email">
These are valid because they are unique and contain no spaces.
Important practical notes:
id="main"is valid.id="main-content"is valid.id="user_1"is valid.id="123abc"is valid in HTML.id="my section"is not valid because it contains a space.
Why this matters:
- If two elements share the same
id, JavaScript and CSS behavior becomes confusing or unreliable. - Some characters may be technically allowed in HTML, but awkward to use in CSS selectors unless escaped.
- Clear naming helps readability and reduces bugs.
So there is a difference between technically valid HTML and practical, easy-to-use naming. In real projects, developers usually choose simple names using letters, numbers, hyphens, and underscores.
Mental Model
Think of an id like a person’s unique employee badge number inside one company.
- Each employee should have a different badge number.
- The badge identifies exactly one person.
- If two people share the same badge number, confusion happens.
- If the badge number contains strange symbols, systems may still store it, but other tools might struggle to use it cleanly.
In the same way, an HTML id should clearly and uniquely identify one element, and it should be easy for CSS, JavaScript, and other developers to work with.
Syntax and Examples
The basic syntax is:
<tag id="unique-name">Content</tag>
Simple example
<h1 id="page-title">Welcome</h1>
You can target it in CSS:
#page-title {
color: darkblue;
}
And access it in JavaScript:
const title = document.getElementById("page-title");
console.log(title.textContent);
Good id examples
<div id="header"></div>
<div id="main-content"></div>
<input id="email">
<section id="product-list"></section>
<p id="user_42"></p>
These are good because they are:
- unique
- readable
- free of spaces
- easy to use in CSS and JavaScript
Bad or risky examples
<div id="main content"></div>
<div id="item#1"></div>
<div id=""></div>
Problems:
main contentcontains a space, which is invalid.item#1may be awkward to use in CSS selectors.- An empty
idis not useful and should be avoided.
Recommended naming style
A common and safe style is lowercase words separated by hyphens:
<section id="user-profile"></section>
<button id="save-button">Save</button>
This style works well across HTML, CSS, and JavaScript.
Step by Step Execution
Consider this HTML:
<h2 id="intro-title">Introduction</h2>
<a href="#intro-title">Jump to title</a>
And this JavaScript:
const element = document.getElementById("intro-title");
console.log(element.textContent);
Step by step:
- The browser reads
<h2 id="intro-title">. - It stores the
idvalueintro-titleas the unique identifier for that element. - The link
<a href="#intro-title">uses that sameidas a fragment. - When clicked, the browser scrolls to the element with
id="intro-title". - In JavaScript,
document.getElementById("intro-title")searches for that element. - The browser returns the
<h2>element. element.textContentgives the textIntroduction.
Now consider a broken case:
<h2 id="intro title">Introduction</h2>
This is invalid because the id contains a space. Tools that depend on that id may not work as expected.
Another broken case:
<div id="box"></div>
<div id="box"></div>
Step by step:
- The first element gets the
idbox. - The second element also gets the
idbox. - The document now has duplicate IDs.
- CSS
#boxmay affect both elements. - JavaScript
getElementById("box")will usually return the first matching element. - This creates bugs because the
idis no longer uniquely identifying one element.
Real World Use Cases
HTML id values are used in many practical situations:
Page navigation
<a href="#pricing">Go to pricing</a>
<section id="pricing">...</section>
This lets users jump to a section of the page.
Form labels and accessibility
<label for="email">Email</label>
<input id="email" type="email">
The for attribute points to the input’s id.
JavaScript DOM access
<button id="toggle-menu">Menu</button>
const button = document.getElementById("toggle-menu");
This is common for attaching events or updating content.
ARIA relationships
<div id="dialog-title">Settings</div>
<div role="dialog" aria-labelledby="dialog-title"></div>
Accessibility features often depend on unique IDs.
Testing hooks in small projects
Some teams use IDs in tests, though many prefer dedicated test attributes for larger apps.
Real Codebase Usage
In real codebases, developers usually treat id values as stable identifiers for important elements.
Common patterns include:
1. Using IDs for one-off unique elements
Examples:
site-headermain-navcheckout-form
These are elements that appear once on the page.
2. Avoiding IDs for repeated UI items
If many elements share the same style or behavior, developers usually use classes instead of IDs.
<li class="product-item">Item 1</li>
<li class="product-item">Item 2</li>
3. Stable hooks for JavaScript
<button id="save-profile">Save</button>
document.getElementById("save-profile").addEventListener("click", saveProfile);
This is useful when exactly one element should be targeted.
4. Guarding uniqueness
In templates or component systems, developers avoid hardcoding the same id in repeated components because it can create duplicates.
Bad example:
<div class="card">
<input id="name">
</div>
<div class="card">
<input id="name">
</div>
Better approach:
<div class="card">
<input id="name-1">
</div>
<div class="card">
<input id="name-2">
</div>
5. Readable naming conventions
Many teams prefer:
- lowercase
- hyphen-separated names
- semantic names based on purpose
Examples:
login-formsearch-inputorder-summary
This helps CSS, JavaScript, and accessibility code stay understandable.
Common Mistakes
Using spaces in IDs
Broken:
<div id="main content"></div>
Fix:
<div id="main-content"></div>
Reusing the same ID multiple times
Broken:
<p id="message">One</p>
<p id="message">Two</p>
Fix: make each id unique, or use a class if multiple elements share the same role.
<p class="message">One</p>
<p class="message">Two</p>
Choosing awkward special characters
Technically some characters may be allowed, but they can be inconvenient in CSS selectors.
Risky:
<div id="item:1"></div>
Safer:
<div id="item-1"></div>
Starting with names that are hard to read
This is valid HTML:
<div id="123abc"></div>
But many developers prefer clearer names such as:
<div id="user-123"></div>
Using IDs when a class is the better tool
If several elements need the same style, use a class.
Broken design idea:
<div id="card"></div>
<div id="card"></div>
Better:
<div class="card"></div>
<div class="card"></div>
Relying on browser quirks
Older HTML versions and CSS rules had more limitations around identifier syntax. Modern HTML is more flexible, but best practice is still to use simple names made of letters, numbers, hyphens, and underscores.
Comparisons
| Concept | Purpose | Must Be Unique? | Best For |
|---|---|---|---|
id | Identifies one specific element | Yes | Single unique elements |
class | Groups multiple elements | No | Shared styles and repeated patterns |
data-* attribute | Stores custom data | No | Metadata for scripts |
id vs class
<div id="main-header"></div>
<div class="card"></div>
<div class="card"></div>
- Use
idwhen there should be exactly one matching element. - Use
classwhen many elements share the same styling or behavior.
Strictly valid vs practically recommended
| Type | Example | Notes |
|---|---|---|
| Valid and recommended | main-content | Easy to read and use |
| Valid but less ideal | 123abc | Allowed in HTML, but less clear |
| Invalid | main content | Contains whitespace |
| Risky | item:1 | May need escaping in CSS |
The safest everyday rule is:
- keep IDs unique
- do not use spaces
- prefer lowercase names with hyphens
Cheat Sheet
Core rules
- An
ididentifies one element in a document. - The value should be unique on the page.
- Do not include spaces, tabs, or line breaks.
- Prefer simple names that work well in HTML, CSS, and JavaScript.
Safe naming pattern
id="main-content"
id="login-form"
id="user-profile"
Avoid
id="main content"
id=""
id="same-id" <!-- used twice -->
Common usage
<a href="#contact">Contact</a>
<section id="contact"></section>
#contact {
padding: 1rem;
}
const contact = document.getElementById("contact");
Best practice
- Use lowercase names
- Separate words with hyphens
- Keep names semantic
- Use
classinstead ofidfor repeated elements
Quick rule of thumb
If only one element should have the name, use an id.
If many elements should share it, use a class.
FAQ
What characters are allowed in an HTML id?
In modern HTML, an id must not contain ASCII whitespace. Many other characters are technically allowed, but simple names with letters, numbers, hyphens, and underscores are easiest to use.
Can an HTML id start with a number?
Yes, in HTML it can. However, names starting with letters are often easier to read and work with, especially in CSS.
Can two elements have the same id?
They should not. An id is meant to be unique within the document.
Are spaces allowed in an id value?
No. An id must not contain spaces or other ASCII whitespace characters.
Should I use id or class?
Use id for one unique element. Use class for styles or behavior shared by multiple elements.
Can I use special characters in an id?
Sometimes yes, but it is usually better to avoid them because CSS selectors may require escaping and the code becomes harder to maintain.
Is an empty id value valid?
It is not useful and should be avoided. In practice, an id should contain a meaningful unique value.
What is the best naming convention for HTML IDs?
A common convention is lowercase words separated by hyphens, such as site-header or user-profile.
Mini Project
Description
Create a small single-page HTML document that demonstrates good id usage for navigation, styling, JavaScript access, and form labeling. This project helps you practice using unique, readable IDs in realistic situations.
Goal
Build a page where IDs are used correctly for section links, a form label, and one JavaScript-controlled button.
Requirements
- Add at least two sections with unique
idvalues. - Add a navigation link that jumps to one of those sections using
href="#...". - Add a form input with a unique
idand a matching<label for="...">. - Add one button with an
idand use JavaScript to respond to a click. - Use simple, readable
idnames without spaces.
Keep learning
Related questions
Allow Only Numeric Input (0-9) in HTML Input Using jQuery
Learn how to allow only digits 0-9 in an HTML input using jQuery, with examples, validation tips, common mistakes, and best practices.
CSS :not() Selector for Excluding a Class or Attribute
Learn how to use the CSS :not() selector to target elements that do not have a specific class or attribute, with examples and common mistakes.
Can HTML Checkboxes Be Readonly? Understanding readonly vs disabled in HTML Forms
Learn why HTML checkboxes do not support readonly, how disabled differs, and practical ways to prevent changes while still submitting values.