The id attribute is a unique identifier which is used to specify a document. The id attribute is used using #(hash) symbol followed by id. The value must be unique amongst all the IDs in the element’s home subtree. Syntax:
<tag id = #Values>
Permitted values for ID attribute: As of HTML5, id must satisfy these three conditions:
- Must be unique in the document.
- Must not contain any space characters.
- Must contain at least one character.
So the value can be all digits, just one digit, include special characters, etc. Just no whitespace. In HTML 5 these values of ids are valid:
<tag id = "#999" > .... </tag > <tag id = "#%LV-||" > .... </tag > <tag id = " ____V" > .... </tag > <tag id = "{}" > .... </tag > <tag id = " ©" > .... </tag >
Note: Using numbers or special characters in the value of an ID may cause trouble in other contexts (CSS, JavaScript). Example:
<tag id = ".\1gfg" > .... <\tag >
This ID is valid in HTML 5 But in CSS, javaScript identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9]. Now we will see examples of valid and invalid ID values in HTML and CSS. Example 1: The value of id is 1gfg and 1geeks which are valid in HTML 5 but not in CSS. So we just get simple output instead of styled output because the value of ID is invalid in CSS.
<!DOCTYPE html> < html >
< head >
< title >Id Attributes</ title >
< style >
#1gfg {
color: #009900;
font-size: 50px;
font-weight: bold;
text-align: center;
}
#1geeks {
text-align: center;
font-size: 20px;
}
</ style >
</ head >
< body >
< div id="1gfg">GeeksforGeeks</ div >
< div id="1geeks">
A computer science portal for geeks
</ div >
</ body >
</ html >
|
Output:
<!DOCTYPE html> < html >
< head >
< title >Id Attributes</ title >
< style >
#gfg {
color: #009900;
font-size: 50px;
font-weight: bold;
text-align: center;
}
#geeks {
text-align: center;
font-size: 20px;
}
</ style >
</ head >
< body >
< div id="gfg">GeeksforGeeks</ div >
< div id="geeks">
A computer science portal for geeks
</ div >
</ body >
</ html >
|
Output:
< html >
< body >
< h1 id=".\1gfg">Hello Geeks!</ h1 >
< button onclick="displayResult()">
Change text
</ button >
< style >
#.\1gfg {
color: green;
}
</ style >
< script >
function displayResult() {
document.getElementById(
".\1gfg").innerHTML = "GeeksForGeeks!";
}
</ script >
</ body >
</ html >
|
Output:
< html >
< body >
< h1 id="gfg">Hello Geeks!</ h1 >
< button onclick="displayResult()">
Change text
</ button >
< style >
#gfg {
color: green;
}
</ style >
< script >
function displayResult() {
document.getElementById(
"gfg").innerHTML = "GeeksForGeeks!";
}
</ script >
</ body >
</ html >
|
Output: