HTML Id


🔹 What is id in HTML?

The id attribute is used to assign a unique identifier to an HTML element.
It is commonly used to:

  • Apply unique styles via CSS

  • Select elements via JavaScript

  • Create internal page links (bookmarks)


🔹 Syntax
<tag id="uniqueId">Content</tag>

Note:

  • The id must be unique on a page.

  • IDs are case-sensitive.


🔹 Example: Styling with id
<style>
  #main-heading {
    color: blue;
    font-size: 24px;
  }
</style>

<h1 id="main-heading">Welcome</h1>

🔹 JavaScript with id

You can use getElementById() to access or manipulate elements.

<p id="demo">Original Text</p>
<button onclick="changeText()">Click Me</button>

<script>
  function changeText() {
    document.getElementById("demo").innerText = "Text Changed!";
  }
</script>

🔹 Linking to an Element Using id

You can create internal links using an anchor and an id.

<a href="#about">Go to About Section</a>

...

<h2 id="about">About Us</h2>
<p>This is the about section.</p>

🔹 Difference Between id and class

Feature id class
Uniqueness Must be unique Can be reused
CSS Selector #id .class
JavaScript getElementById() getElementsByClassName()

Practice Questions

Q1. Create a paragraph with an id and style it using CSS.

Q2. Add a heading with id="title" and change its color to red.

Q3. Use JavaScript to change the content of a <div> with id="output".

Q4. Create a button that updates a paragraph with a specific id.

Q5. Use id="contact" and create a link that jumps to that section.

Q6. Add an input box with a unique id and set its value using JavaScript.

Q7. Create a list where one item has a special style via id.

Q8. Demonstrate an internal link navigation using id.

Q9. Apply font-style: italic to an element with a specific id.

Q10. Create a section with id="faq" and a link that jumps to it.


Go Back Top