HTML Id Attribute

HTML Id Attribute Tutorial

1. HTML Id Attribute

The id attribute refers to a unique value for an HTML element. This HTML id value can be used with CSS and JavaScript to perform certain task.

2. HTML id with CSS

In CSS, if you want to select an element with a specific id, write a hash (#) character, followed by the id of the element.

3. Example:

Use the HTML id "myid" with CSS:

<style>    
#myid {    
    background-color:
lightpink;    
    color: black;    
    padding: 40px;    
    text-align: center;    
}     
</style>    
<h1
id="myid">Example of HTML id</h1>

4. Difference between HTML Class and ID

An HTML class name can be used by multiple elements while An HTML element can only have one unique id that belongs to that single element.

5. Example:

  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4. <style>    
  5. /* Style the element with the id "myid" */    
  6. #myid {    
  7.     background-color: pink;    
  8.     color: black;    
  9.     padding: 40px;    
  10.     text-align: center;    
  11. }    
  12.     
  13. /* Style all elements with the class name "fruit" */    
  14. .fruit {    
  15.     background-color: orange;    
  16.     color: white;    
  17.     padding: 10px;    
  18. }     
  19. </style>    
  20. </head>    
  21. <body>    
  22.     
  23. <h2>Difference Between Class and ID</h2>    
  24.     
  25. <h1 id="myid">My Favorite Fruits</h1>    
  26.     
  27. <h2 class="fruit">Mango</h2>    
  28. <p>The Kinkg of all fruits.</p>    
  29.     
  30. <h2 class="fruit">Orange</h2>    
  31. <p>Full of Vitamin C</p>    
  32.     
  33. <h2 class="fruit">Apple</h2>    
  34. <p>An apple a day, keeps the doctor away.</p>    
  35.     
  36. </body>    
  37. </html>    

6. Output:

7. HTML id with JavaScript

You can use HTML id with JavaScript getElementById() method to access an element with a specified id.

8. Example:

<!DOCTYPE html>    
<html>    
<body>    
<h2>
HTML id with JavaScript</h2>    
<h1
id="myid">Hello samtpoint</h1>    
<button
onclick="displayResult()">Change text</button>    
<script>    

function displayResult() {    
    document.getElementById("myid").innerHTML = "All the best for future!";    
}    
</script>    
</body>    
</html>