HTML Id
The HTML id attribute is used to specify a unique id for an HTML element.
Syntax
Step 1: A hash character (#), followed by an id name.
Step 2: Then, define the CSS properties within curly braces {}.
#idName {
property: value;
}
Step 3: Use the id attribute to set id for the element.
<tagName id="idName">
Note: You cannot have more than one element with the same id in an HTML document.
HTML Id Attribute
The id attribute specifies a unique alphanumeric identifier to be associated with an element.
Example
<!DOCTYPE html>
<html>
<head>
<style>
#demo {
background-color: tomato;
color: white;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<h1 id="demo">Heading of the Page</h1>
<p>Paragraph of the page.</p>
</body>
</html>
How to Use the id Attribute
Accessing naming an element is important to being able to access it with a style sheet, a link, or a scripting language.
Name should be unique to a document and should be meaningful for example; although id="x1" is perfectly valid, id="Paragraph1" might be better.
Values for the id attributemust begin with a letter (A–Z or a–z) and may be followed by any number of letters, digits, hyphens, or periods.
Practically , a period character should not be used within an id value given the use of these values in scripting languages and possible confusion with class names.
HTML id Attribute for Styling
As same as the class attribute, the id attribute is also used by style sheets for accessing a particular element. For example, #Paragraph1 {color: red;}
Example
<style>
#demo {
background-color: tomato;
color: white;
padding: 20px;
text-align: center;
}
</style>
HTML id Attribute for target Element with anchor tag
Once an element is named using id, it also is a potential destination for an anchor, for example:
Example
<a href="#main">Go to main</a>
<div id="main">This is the main of the page.</div>
HTML id Attribute for JavaScript
Once elements are named with id, they should be easy to manipulate with a scripting language. Commonly they are referenced using the DOM method getElementById().
Example
<h1 id="demo">Heading of the Page</h1>
<button onclick="myFunction()">Click me!</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World!";
}
</script>
Note: The main problem with the id attribute is that, for some elements, particularly <form> controls and images, the <name> attribute already serves its function. You should be careful when using both <name> and id together, especially when using older element syntax with newer styles.
A complete list of all HTML tags, see HTML Tag Reference.