Attributes, id and class
An attribute gives extra information about an element. It is written inside the opening tag as name="value". You already used href on links and src on images.
Attributes are like the settings of an element: where a link goes, which image to show, whether a field is required, which language the page is in. Every element has some attributes it understands, and a few - id, class, title, hidden, lang - work on almost every element (they're called global attributes).
<a href="https://terixto.com" target="_blank" title="Open Terixto">Visit Terixto</a>
<img src="logo.png" alt="Terixto logo" width="120">id - one unique name
An id names one element on the page. No two elements may share the same id. You can jump to it with a link like href="#contact", and CSS and JavaScript can find it.
class - a group name
A class can be shared by many elements, and one element can have several classes separated by spaces. CSS uses classes to style groups of elements.
The difference matters in practice: think of id as a person's Aadhaar number (only one person has it) and class as their job title (many people share it). Use ids for one-of-a-kind things - a jump target, a form field's label connection - and classes for styling and grouping.
<!DOCTYPE html>
<html>
<head>
<style>
.price { color: green; font-weight: bold; }
.sale { background: #fff3cd; }
</style>
</head>
<body>
<a href="#contact">Go to contact</a>
<p class="price">₹499</p>
<p class="price sale">₹299 (on sale)</p>
<div style="height: 600px"></div>
<h2 id="contact">Contact us</h2>
<p>Email: support@example.com</p>
</body>
</html>▶ Try it yourselfdata-* attributes
You can store your own small values with attributes that start with data-. JavaScript reads them with element.dataset.
<button data-product-id="B0123" data-price="499">Add to cart</button>
<script>
const btn = document.querySelector("button");
console.log(btn.dataset.productId); // Output: B0123
console.log(btn.dataset.price); // Output: 499
</script>Boolean attributes
Some attributes need no value. Just writing them switches them on: disabled, checked, required, hidden, readonly.
- Attributes add settings to elements as name="value".
- id is unique on the page; class can be shared and combined.
- data-* attributes store your own values for JavaScript.
- Boolean attributes are on just by being present.
