HTML id Global Attribute

Description

The id HTML global attribute specifies a unique identifier for an HTML element. It can be used on any HTML element, and its value must be unique within the document. The id attribute is used for a variety of purposes, including:

  • Styling: CSS selectors can be used to target elements with specific id values. This allows you to apply unique styles to individual elements.
  • Scripting: JavaScript can be used to access and manipulate elements with specific id values. This allows you to dynamically control the behavior of your web pages.
  • Linking: You can use fragment identifiers to link directly to specific elements on a page. This is useful for creating navigation within a long page or for sharing specific content with others.

Here is an example of how to use the id attribute:

<h1 id="main-heading">This is the main heading</h1>
<p>This is some text.</p>

This CSS selector would target the h1 element with the id value main-heading:

#main-heading {
  color: red;
}

This JavaScript code would access the p element with the id value my-paragraph:

const myParagraph = document.getElementById("my-paragraph");
// Do something with the paragraph element

This fragment identifier would link directly to the h1 element with the id value main-heading:

<a href="#main-heading">Go to the main heading</a>

Syntax

#id { ... }

Values

  • idA name used to assign to the ID. Use only letters of the alphabet ( AZ, az ), numbers, hyphens, underscores.

Example

<!DOCTYPE html>
<html>
<head>
<title>Global Attribute id</title>
<style>
#main {
text-align:center;
color:red;
}
#index {
color:blue;
}
</style>
</head>
<body>
<h1 id="main">First level heading.</h1>
<p id="index">Paragraph with assigned id as a style identifier.</p>
<a href="#main">Using id as an anchor</a> (throws to the specified id).
<p>Using JavaScript scripts (changing elements with a specific id):</p>
<script>
function chg() {
var x = document.getElementById("main");
x.style.color = "white";
x.style.backgroundColor = "orange";
}
</script>
<button onclick="chg()">Click!</button>
</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML id Global Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 14th October 2023