CSS Portal

HTML id Global Attribute

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
id
HTML Global AttributeThis global attribute is supported by all modern browsers.
Updated 14th October 2023

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>
Open in editor

Browser Support

The following information will show you the current browser support for the HTML id global attribute. Hover over a browser icon to see the version that first introduced support for this HTML global attribute.

This global attribute is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee