HTML ID And Class
You can use both an HTML ID and class in one HTML element. An ID is a unique identifier for an element and should be used only once on a page, while a class can be used multiple times. To apply both an ID and class to an element, you can write the ID selector first, followed by a period (.) and the class selector:
An HTML ID is a unique identifier that is used to specify a specific element on a web page. The ID is defined by the
Here’s an example of using an ID in HTML:
<h1 id="page-title">Welcome to My Website</h1>
In this example, the heading element has an ID of “page-title”. This ID can be used in CSS to style the heading specifically:
const pageTitle = document.getElementById("page-title");
pageTitle.innerHTML = "New Page Title";
For Regular Off – Campus Job, Updates Join:- Click Here
An HTML class is a way to group similar elements together in HTML and assign them a common style in CSS. A class can be applied to multiple elements on a page, unlike an ID which should be unique. The class is defined by the
Here’s an example of using a class in HTML:
<p class="highlight">This is a highlighted paragraph.</p>
<p class="highlight">Another highlighted paragraph.</p>
In this example, two paragraphs have the class “highlight”. This class can be used in CSS to style both paragraphs similarly:
const highlights = document.getElementsByClassName("highlight");
for (let i = 0; i < highlights.length; i++)
highlights[i].innerHTML = "This is a modified highlight.";
Using classes in HTML allows you to separate the structure of your content from the presentation of your content, making it easier to maintain and update your website.
Different between HTML ID And Class
- Unique: An ID must be unique within a web page, meaning that no two elements can have the same ID.
- Selector: An element with an ID can be selected using the “#” symbol followed by the ID name in CSS. For example, if an element has an ID of “header”, it can be selected using “#header” in CSS.
- Style: An ID can be used to apply a unique style to a single element on a web page.
- Usage: IDs are used when a unique style is needed for a single, specific element on a web page.
- Non-Unique: A class can be used on multiple elements on a web page, meaning that several elements can have the same class.
- Selector: An element with a class can be selected using the “.” symbol followed by the class name in CSS. For example, if an element has a class of “highlight”, it can be selected using “.highlight” in CSS.
- Style: A class can be used to apply a style to multiple elements on a web page.
- Usage: Classes are used when a style needs to be applied to multiple elements on a web page.