HTML ID

HTML ID is used to identify a HTML Element uniquely in HTML document.

The id attribute is most used to point to a style in a style sheet (CSS Code), and by JavaScript (via the Document Object Model, or DOM) to manipulate the element with the specific id.

HTML ID Syntax


<tag_name id="id_name"> Tag content Here </tag_name>
  

Why HTML Id

HTML id attribute is very important, because it provide unique identity to an HTML Element. There are many things which can be done with HTML id, below we are listing them.

  • We can use HTML Id attribute value to styling that element by CSS.
  • A HTML can be find by JavaScript using element ID attribute.
  • For backend coding we use id for getting value to from them to store in database or assign value to that html element.
  • HTML id should be unique in a HTML Page, 2 or more HTML Element can’t have same HTML id in a web page.
  • HTML id is case-sensitive means hello_p and hello_P are different
  • HTML id name does not allow any space.
  • A HTML Element can have only one id attribute name.

HTML ID Example

<p id="myP"> This is p with id myP </p>
<a id="myA"> Anchor tag with id myA </a>
  

Use of HTML Id with CSS

We can use HTML Id in assigning some CSS style on that HTML element. We use #id_name to find an element in HTML document. Let’s take an example.

Id Example with CSS

<head>
   <style type="text/css">
      #p1{
            color:blue;
            font-size:23px;
          }
      #p2{
            color:lime;
            font-size:14px;
          } 
   </style> 
</head>
<body>
   <p id="p1"> Hello i'm a paragraph with id p1 </p>
   <p id="p2"> This is other paragraph, my id is p2 </p>
</body>

Output

Hello i'm a paragraph with id p1

This is other paragraph, my id is p2

Use of HTML Id with JavaScript

Same as CSS we can identify an element in HTML Document and can write some JavaScript code for that element by using document.getElementById("id_name")

Id Example with JavaScript

<head>
   <script type="text/javascript">
      function changeColor(){
        var p_element = document.getElementById("change_p");
        p_element.style.color = "red";
      } 
   </style> 
</head>
<body>
   <input type="button" onclick= "changeColor();" name="ok" value ="Click Me" />
   <p id="change_p"> My text color is going to chage </p>
</body>

Output


My text color is going to chage

Email Us: advertise@gdatamart.com

Donate Us: Support to GDATAMART

© 2023 GDATAMART.COM (All Rights Reserved)