HTML id attribute

Definition and Usage

id The attribute specifies the unique id of an HTML element. (This value must be unique in the HTML document).

id The attribute is most commonly used to point to styles in a stylesheet and to manipulate elements with a specific id using JavaScript (via HTML DOM).

id The attribute can also be used as a link anchor (link anchor).

See Also:

HTML Tutorial:HTML id

HTML Tutorial:HTML attributes

CSS Tutorial:CSS syntax

CSS Reference Manual:CSS #id Selector

HTML DOM Reference Manual:HTML DOM getElementById() Method

HTML DOM Reference Manual:HTML DOM id Attribute

HTML DOM Reference Manual:HTML DOM Style object

Example

Example 1

Use the id attribute to change a piece of text with JavaScript:

<html>
<body>
<h1 id="myHeader">Hello World!</h1>
<button onclick="displayResult()">Change Text</button>
<script>
function displayResult() {
  document.getElementById("myHeader").innerHTML = "Have a nice day!";
}
</script>
</body>
</html>

Try it yourself

More examples are provided below the page.

Syntax

<element id="id">

Attribute Value

Value Description
id

Specify a unique id for the element. Naming rules:

  • Must contain at least one character
  • Cannot contain any space characters

More Examples

Example 2

Use the id attribute to link to an element within the page that has a specified id:

<html>
<body>
<h2><a id="top">Some Title</a></h2>
<p>Many many texts ....</p>
<p>Many many texts ....</p>
<p>Many many texts ....</p>
<a href="#top">Return to Top</a>
</body>
</html>

Try it yourself

Example 3

Use the id attribute to style text with CSS:

<html>
<head>
<style>
#myHeader {
  color: red;
  text-align: center;
}
</style>
</head>
<body>
<h1 id="myHeader">CodeW3C.com is the best!</h1>
</body>
</html>

Try it yourself

Browser support

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Support Support Support Support Support