learn2kode.in

HTML – IDs

In HTML, an ID is a unique identifier assigned to a single element. IDs help you target specific elements using CSS, JavaScript, and internal page links.

What is an ID?

Example

<p id="intro">This is an introduction paragraph.</p>

Using ID in CSS

To style an element with an ID:

<style>
  #intro {
    color: blue;
    font-size: 20px;
  }
</style>

<p id="intro">Styled with an ID selector!</p>

Using ID in JavaScript

JavaScript can fetch an element using its ID:

<p id="message">Hello</p>

<script>
  document.getElementById("message").innerHTML = "Updated using JavaScript!";
</script>

Using ID for Page Navigation (Anchors)

IDs allow jump links within a page:

<a href="#section2">Go to Section 2</a>

<h2 id="section2">Section 2</h2>
<p>This is the second section.</p>

Rules for Using IDs

Rule Explanation
Unique No two elements can have the same ID
One per element A single element cannot have multiple IDs
Case-sensitive #Header#header
Use letters first ID names should not start with numbers

Common Use Cases

Example: ID in a Form

<label for="name">Name:</label>
<input type="text" id="name" name="name">

The for attribute links the label directly to the element with matching ID.