iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

HTML Id

An id is a unique identifier - exactly one element per page. Use it for fragment links, label-for-input pairs, and JavaScript targeting.

When to reach for id

EXAMPLE
<!-- Fragment link (jumps the browser to the element) -->
<nav>
  <a href='#features'>Features</a>
  <a href='#pricing'>Pricing</a>
</nav>

<section id='features'>
  <h2>Features</h2>
  <p>...</p>
</section>

<section id='pricing'>
  <h2>Pricing</h2>
  <p>...</p>
</section>


<!-- Label + input pairing - clicking the label focuses the input -->
<label for='email'>Email</label>
<input id='email' type='email' name='email' required />

<!-- aria-describedby uses ids to associate help text -->
<label for='pass'>Password</label>
<input id='pass' type='password' aria-describedby='pass-help' />
<p id='pass-help' class='text-sm text-gray-500'>At least 12 characters.</p>


<!-- JavaScript by id is faster than by class -->
<script>
  const el = document.getElementById('features');
  el.scrollIntoView({ behavior: 'smooth' });
</script>


<!-- CSS by id (rare - prefer classes for styling) -->
<style>
  /* Higher specificity than classes; use sparingly */
  #features { padding: 4rem 0; }
</style>


<!-- Common mistakes -->
<!-- BAD: duplicate ids -->
<button id='save'>Save</button>
<button id='save'>Save again</button>  <!-- breaks JS + accessibility -->

<!-- BAD: spaces in id -->
<div id='main content'>          <!-- not allowed -->

<!-- GOOD: kebab or camelCase, unique -->
<div id='main-content'>

Why it matters

Ids are unique; classes repeat. Use ids for fragment links, form labels, and aria-* associations. For styling, prefer classes - ids make CSS hard to override and force you into specificity wars.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
<!DOCTYPE html>
<html>
<head>
    <title>HTML Id</title>
</head>
<body>

<h1>HTML Id</h1>
<p>This is a demo page for the "HTML Id" lesson.</p>

</body>
</html>
Try it Yourself »

Exercise

Give this section an identifier so it can be linked with a URL fragment.

<section ="pricing">…</section>

Test yourself

Q1. Each ID on a page must be…
Q2. A CSS id selector uses…
Q3. Find by id in JS with…

Discussion

Loading…