Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

HTML Id Attributes

  • Difficulty Level : Basic
  • Last Updated : 17 Sep, 2021

Example: In this example, we simply style the element with id “geeks”.

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.

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:

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 # 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: 

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: 
 

id attributes

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 id attribute. 

Example: 

html




<!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: 
 

id selector

Supported Browsers: 
 

  • Google Chrome
  • Edge 12 and above
  • Firefox 32 and above
  • Internet Explorer
  • Mozilla
  • Opera
  • Safari

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!