HTML Id Attribute
This style will be applied for single element.
The id can be identified in css as #name
The id name in id attribute is also used in js to change or add the styles or classnames.
The id attribute takes a id name, which consits a set of styles, The id name is kept in the attribute and only single id name is kept without any space.
Syntax: <tagname id="idname" > Content <tagname>
Example
<p id="p1">This is a styled p element using p1 id</p>
<p id="p2">This is a styled p element using p2 id</p>
It is Different from class
S.No
id
Class
1
Used to uniquely identify a single HTML element on a page.
Used to identify a group of HTML elements that share a common purpose or style.
2
Each element can have only one id, and the id values must be unique within the entire HTML document.
Multiple elements can have the same class, and an element can have multiple classes separated by spaces.
3
It is often used to target specific elements for styling or scripting purposes.
It is widely used for applying common styles to multiple elements or for selecting elements through CSS and JavaScript.
4
To select an element with a particular id in CSS, you use the hash (#) symbol followed by the id value (e.g., #myElement).
To select elements with a specific class in CSS, you use a period (.) followed by the class name (e.g., .myClass).
5
In JavaScript, you can easily select an element by its id using document.getElementById('myElement').
In JavaScript, you can select elements by class using methods like document.getElementsByClassName('myClass').
Example
<!DOCTYPE html>
<html>
<head>
<style>
.topic {background-color: red;text-align:right }
#topic {background-color: orange;text-align:center }
</style>
</head>
<body>
<h1 id="topic">Heading</h1>
<p class="topic">This is a Paragraph</p>
</body>
</html>
Id used in Javascript
Example
<!DOCTYPE html>
<html>
<head>
<style>
#unique-paragraph {
font-weight: bold;
}
</style>
</head>
<body>
<p id="target-element">This is the target element.</p>
<script>
const targetElement = document.getElementById('target-element');
// Now you can perform actions on the targetElement
</script>
</body>
</html>