The id attribute is a unique identifier which 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 # symbol followed by id.
Syntax:
<tag id=""></tag>
Example:
<!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:
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 on a precise element in your script, then you can use id attribute.
Example:
<!DOCTYPE html> < html > < head > < title >use 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:
Supported Browsers: The browser supported by Id Attribute are listed below:
- Google Chrome
- Internet Explorer
- Mozilla
- Opera
- Safari