Table of Contents

HTML - Element's unique identifier (Id Attribute)

About

The DOM specification gives the concept of an element's unique identifier (ID)

An element's unique identifier can be used for a variety of purposes, most notably as a way to:

Selection

The first purpose of an id is to be able to select the element.

getElementById Function

With the document getElementById function

Demo:

<h1 id="id1">Heading content</h1>
console.log("The content of the element with the id `id1` is "+document.getElementById("id1").innerHTML);

Selector API

With the selector API (used by css), see the page: Selector API - ID (Unique Identifier) attribute

Shorthand notation

With Javascript, window lets you select the id directly.

<h1 id="id1">Heading</h1>
console.log("The content of the element with the id `id1` is "+window.id1.innerHTML);

Syntax

It is non-conforming to have two id attributes with the same value. This will be hard to debug. Duplicate IDs lead to the wrong element being selected, with sometimes disastrous effects whose cause is hard to determine.

HTML4

Tokens:

HTML5

Tokens:

There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.

Documentation / Reference