Home » HTML ID

HTML ID

HTML ID

Introduction

HTML Id is essential for providing a unique identifier to elements within a document. This identifier plays a crucial role in styling through CSS and dynamic manipulation using JavaScript.

Syntax
<tag id="value">
HTML

Example 1: CSS Styling

Styling an element with the id “main-heading” in CSS:

<!DOCTYPE html>
<html>
<head>
  <style>
    #main-heading {
      font-size: 24px;
      color: #3498db;
      text-align: center;
      margin-bottom: 20px;
    }

    #sub-heading {
      font-size: 18px;
      color: #2ecc71;
      text-align: center;
    }
  </style>
</head>
<body>
  <h1 id="main-heading">Welcome to our Website</h1>
  <h2 id="sub-heading">Exploring the World of Coding</h2>
</body>
</html>
HTML
html-id-syntax.png

Example 2: JavaScript Interaction

Using the id attribute in JavaScript to validate a form:

<!DOCTYPE html>
<html>
<head>
<title> Form Validation </title>
<script>
function validateForm() {
  var name = document.getElementById("name").value;
  var email = document.getElementById("email").value;

  if (name === "" || email === "") {
    alert("Name and Email are required!");
    return false;
  }

  alert("Form submitted successfully!");
  return true;
}
</script>
</head>
<body>
  <form onsubmit="return validateForm()">
    Name: <input type="text" id="name">
    <br>
    Email: <input type="email" id="email">
    <br>
    <input type="submit" value="Submit">
  </form>
</body>
</html>
HTML
JavaScript-interaction.png

Difference Between Class and ID in HTML

  • Class: Used by multiple HTML elements.
  • ID: Must be unique within the document.

HTML Bookmarks with ID and Links

Creating bookmarks for navigation within a page:

<h2 id="section1">Section 1</h2>
<a href="#section1">Jump to Section 1</a>

HTML

Conclusion

This attribute provides a unique identifier for elements, enabling targeted styling and dynamic JavaScript interactions. Remember, it must be unique within the document, and its case sensitivity should be considered.

Frequently Asked Questions

1. Can an HTML element have multiple id attributes?

Ans: No, an HTML element can have only one id’s attribute. It must be unique within the document.


2. Is the id attribute case-sensitive?

Ans: Yes, the id attribute is case-sensitive. “myId” and “myID” are considered different.


3. Can I use the id’s attribute on any HTML element?

Ans: Yes, the id’s attribute is versatile and can be used on any HTML element.