Episode 14 of 17

ID's and Classes

Learn to use id and class attributes to identify and group HTML elements for CSS and JavaScript.

IDs and Classes

The id and class attributes are how you identify and group HTML elements for targeting with CSS and JavaScript.

The id Attribute

An id gives an element a unique identifier. Each id must be unique on the page — no two elements can share the same id.

<h1 id="main-title">Welcome</h1>
<div id="hero-section">
    <p>Hero content here.</p>
</div>

The class Attribute

A class groups elements together. Multiple elements can share the same class, and one element can have multiple classes.

<p class="intro">First paragraph.</p>
<p class="intro highlight">Second paragraph (two classes).</p>
<p class="intro">Third paragraph.</p>

id vs class

Featureidclass
UniquenessMust be unique on the pageCan be reused on many elements
Multiple valuesOne id per elementMultiple classes per element
CSS selector#id-name.class-name
JS selectorgetElementById()getElementsByClassName()
SpecificityHigher (overrides class styles)Lower
Best forUnique elements (header, footer)Repeated patterns (cards, buttons)

Using IDs and Classes in CSS

<style>
    /* ID selector — targets ONE specific element */
    #main-title {
        color: #6c5ce7;
        font-size: 2.5rem;
    }

    /* Class selector — targets ALL elements with this class */
    .intro {
        font-size: 1.1rem;
        line-height: 1.7;
        color: #555;
    }

    .highlight {
        background-color: #fffbcc;
        padding: 4px 8px;
    }
</style>

Using IDs and Classes in JavaScript

<script>
    // Select by ID
    const title = document.getElementById('main-title');
    title.textContent = 'Updated Title';

    // Select by class
    const intros = document.querySelectorAll('.intro');
    intros.forEach(p => p.style.color = 'blue');
</script>

Naming Best Practices

  • Use lowercase with hyphens: hero-section, nav-bar, card-title
  • Be descriptive: product-card is better than box1
  • Don't start with a number: section-1 is okay, 1-section is not
  • Avoid unnecessary IDs — use classes by default, IDs only when you truly need uniqueness

Anchor Links with IDs

IDs also enable anchor links — clicking a link scrolls to that element:

<a href="#contact">Jump to Contact</a>

<!-- Further down -->
<section id="contact">
    <h2>Contact Us</h2>
</section>

Key Takeaways

  • id is unique — only one element per page
  • class is reusable — multiple elements can share it
  • Use #id and .class selectors in CSS
  • Prefer classes over IDs for styling
  • Use descriptive, hyphenated names