Skip to content

ID (HTML)

In one line

The id attribute gives an HTML element a unique identifier on the page, used for styling, scripting, and anchoring.

In simple words

The id attribute assigns a unique name to a single HTML element on a page. No two elements on the same page should share the same id. This uniqueness makes ids useful for targeting one specific element — in CSS, JavaScript, or as a link anchor.

In CSS, an id is targeted with a hash: #header { ... }. In JavaScript, document.getElementById('header') returns that exact element. In URLs, #section-2 scrolls the page to the element with that id.

Because ids must be unique, they are not the right tool for reusable styles — use classes for that. Reserve ids for elements that appear once per page and need to be addressed individually, like a main header, a specific form, or a navigation bar.

Example

html
<header id="main-header">Welcome</header>

<style>
  #main-header { background: #2563eb; color: white; }
</style>

<script>
  const header = document.getElementById("main-header");
  console.log(header.textContent); // "Welcome"
</script>

id="main-header" uniquely identifies this header. CSS targets it with #main-header, JS with getElementById.

Common confusions

  • Confused with: class

    The difference: An id is unique per page and targeted with #id; a class can be shared by many elements and is targeted with .class. Use ids for one-of-a-kind elements, classes for repeated styles.

Related terms

Related Resources

Related Lessons

  • HTML

    The id attribute is introduced with HTML

Learn the fundamentals

Deepen your understanding with structured lessons on this topic.

View lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary