-
Hajipur, Bihar, 844101
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)
<tag id="uniqueId">Content</tag>
Note:
The id
must be unique on a page.
IDs are case-sensitive.
id
<style>
#main-heading {
color: blue;
font-size: 24px;
}
</style>
<h1 id="main-heading">Welcome</h1>
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>
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>
id
and class
Feature | id |
class |
---|---|---|
Uniqueness | Must be unique | Can be reused |
CSS Selector | #id |
.class |
JavaScript | getElementById() |
getElementsByClassName() |
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.
Q1: What is the main purpose of the id attribute?
Q2: How do you select an element with id="main" in CSS?
Q3: Which JavaScript method is used to select an element by id?
Q4: Can two elements have the same id?
Q5: Which is valid HTML?
Q6: What is the default behavior of <a href="#section1">?
Q7: How many times can you use the same id on a page?
Q8: What symbol is used to select an id in CSS?
Q9: Which of the following is not a correct use of id?
Q10: What happens if you use the same id on multiple elements?