id

The id attribute in HTML provides a unique identifier for an element, enabling specific styling and scripting, while ensuring that each ID is unique within a page.

id Attribute

The id attribute assigns a unique identifier to an HTML element, allowing targeted styling, scripting, and navigation. Each id must be unique within a document.

Syntax

index.html
<element id="unique-id">
  <!-- Content -->
</element>

Example

index.html
<p id="preamble"></p>

Styling an Element with id

My Header
index.html
<h1 id="myHeader">My Header</h1>

Key Points About id

  • id names are case-sensitive.
  • They must start with a letter (not a number).
  • Spaces and special characters are not allowed.

Difference Between id and class

  • An id is unique to a single element.
  • A class can be used for multiple elements.

Using id and class

My Cities
London

London is the capital of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

index.html
<h1 id="myHeader">My Cities</h1>
<h2 class="city">London</h2>
<p>London is the capital of England.</p>
<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>

Creating Bookmarks with id

The id attribute can be used to create bookmarks for quick navigation within a webpage.

Adding a Bookmark

Jump to Chapter 4

Jump to Chapter 10

Chapter 1

Introduction to the topic.

Chapter 2

Further exploration.

Chapter 4

In-depth details.

Chapter 10

Advanced concepts.

index.html
<p><a href="#C4">Jump to Chapter 4</a></p>
<p><a href="#C10">Jump to Chapter 10</a></p>
<h2>Chapter 1</h2>
<p>Introduction to the topic.</p>
<h2>Chapter 2</h2>
<p>Further exploration.</p>
<h2 id="C4">Chapter 4</h2>
<p>In-depth details.</p>
<h2 id="C10">Chapter 10</h2>
<p>Advanced concepts.</p>

Linking to a Bookmark from Another Page

index.html
<a href="page.html#chapter4">Jump to Chapter 4</a>

Best Practices

  • Each id must be unique within the document.
  • Avoid spaces or special characters in id values.
  • Use id for single-use elements and class for reusable styles.

Conclusion

The id attribute is an essential tool for targeting specific HTML elements in CSS and JavaScript. It facilitates styling, navigation, and dynamic content manipulation. Proper use of id ensures a structured and efficient webpage, allowing seamless interaction between styling and scripting elements.