HTML Id Attributes
In this article, we will know how to identify the specific HTML element by its id using HTML id Attribute, along with understanding its implementation through the examples.
The id attribute is a unique identifier that is used to specify the document. It is used by CSS and JavaScript to perform a certain task for a unique element. In CSS, the id attribute is used using the # symbol followed by id. quotes are not mandatory in tag=” ” in all cases. But writing with quotes is a good practice.
Syntax:
<tag id=""></tag>
Note: This is a global attribute, it can be used in all the tags.
Example 1: In this example, we simply style the element with id “geeks”.
HTML
<!DOCTYPE html> < html > < head > < style > #geeks { color: green; } </ style > </ head > < body > < h2 >Welcome to GeeksforGeeks</ h2 > < h1 id = "geeks" >Hi Geeks!</ h1 > </ body > </ html > |
Output:

HTML id Attribute
Example 2: In this example, we are adding the styling properties to the specific id attribute value by fetching its id value.
HTML
<!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:

Adding the style properties to the specific id attribute value
Note: In HTML5, id attributes can be used by any HTML tag but in HTML 4.01 there are some restriction to use id attributes. It can not be used by <base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title> tag. In HTML4.01 id can not start with number.
Use of ID attributes in JavaScript: In JavaScript, the id attribute is used to manipulate the text, if you want to make changes to a precise element in your script, then you can use the id attribute.
Example 3: This example describes getting the id attribute value in Javascript through getElementById() Method.
HTML
<!DOCTYPE html> < html > < head > < title >Using the id in Javascript</ title > < style > #geeks { font-size: 50px; color: #009900; font-weight: bold; margin-bottom: 10px; } </ style > </ head > < body > < div id = "geeks" >GeeksforGeeks</ div > < button onclick = "geeksResult()" >Display text change</ button > < script > function geeksResult() { document.getElementById("geeks").innerHTML = "A computer science portal for geeks"; document.getElementById("geeks").style.color = "black"; } </ script > </ body > </ html > |
Output:

Getting the id attribute value using getElementById() Method
Supported Browsers:
- Google Chrome
- Edge 12 and above
- Firefox 32 and above
- Opera
- Safari
Please Login to comment...