← Learning Hub
Intermediate

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).

Example
<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.

Example
<!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 yourself

data-* attributes

You can store your own small values with attributes that start with data-. JavaScript reads them with element.dataset.

Example
<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.

Write attribute values in double quotes and use lower-case names. It keeps your HTML clean and easy to read.
Key points
  • 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.

📝 Test yourself

1. How many elements on a page may have id="menu"?
2. How do you give one element two classes?
3. Fill in the start of a custom attribute name:
<li -colour="red">