← Back to Chapters

jQuery ID & Class Selectors

? jQuery ID & Class Selectors

? Quick Overview

jQuery ID and Class selectors are used to select HTML elements based on their id or class attributes. They are among the most commonly used selectors because they are simple, fast, and easy to understand.

? Key Concepts

  • ID selector starts with # and targets a unique element
  • Class selector starts with . and targets multiple elements
  • Selectors are passed inside $()
  • Actions are applied using jQuery methods

? Syntax / Theory

  • $("#id") → Select element by ID
  • $(".class") → Select elements by class
  • ID must be unique in a page
  • Class can be reused on multiple elements

? Code Example — ID Selector

? View Code Example
// Select element using ID and change its text
$("#title").text("ID Selector Applied");

? Code Example — Class Selector

? View Code Example
// Select all elements with class and apply CSS
$(".box").css("background-color","lightblue");

? Live Output / Explanation

The ID selector updates only one specific element, while the class selector applies changes to all elements sharing the same class name.

? Interactive Example

Clicking a button can trigger jQuery to style elements dynamically using ID or class selectors.

? View Code Example
// Button click applies styles using both selectors
$("#btn").click(function(){
$("#demo").css("color","red");
$(".group").css("font-weight","bold");
});

? Use Cases

  • Updating a single element using ID
  • Styling groups of elements using class
  • Handling events on specific UI components
  • Building dynamic interactive pages

✅ Tips & Best Practices

  • Use ID selector when targeting a single element
  • Prefer class selectors for reusable styles
  • Avoid duplicate IDs in HTML
  • Keep selector names meaningful

? Try It Yourself

  • Create a button and change text using ID selector
  • Apply background color to multiple elements using class
  • Combine ID and class selectors in one function