Mastering jQuery Selectors

Tutorial 1 of 5

1. Introduction

This tutorial aims to introduce how to master jQuery selectors, a fundamental aspect of manipulating HTML documents with jQuery. By the end of this tutorial, you will be able to select elements by their ID, class, and element type.

Prerequisites: Fundamental knowledge of HTML, CSS, and JavaScript is necessary. Prior exposure to jQuery is beneficial but not a hard requirement.

2. Step-by-Step Guide

jQuery selectors are the way we can select and manipulate HTML elements. They are based on the existing CSS Selectors, and in addition, they have some custom selectors. Here's a detailed explanation of the primary selectors:

  • Element Selector: The element selector selects elements based on the element type.
  • #ID Selector: The ID selector uses the id attribute of an HTML tag to find the specific element.
  • .Class Selector: The Class selector finds elements with a specific class.

Best Practices:

  • Always use a specific selector. It reduces the search time, especially for larger DOM structures.
  • Use class selectors instead of tag selectors whenever possible. It increases reusability and reduces conflicts.

3. Code Examples

Here are some code examples demonstrating jQuery selectors:

Element Selector

$("p").css("background-color", "yellow");

This code selects all <p> elements and changes their background color to yellow.

#ID Selector

$("#test").css("background-color", "yellow");

This code selects the HTML element with id="test" and changes its background color to yellow.

.Class Selector

$(".test").css("background-color", "yellow");

This code selects all elements with class="test" and changes their background color to yellow.

4. Summary

In this tutorial, we have covered how to select elements using jQuery by their type, ID, and class. These selectors form the basis of jQuery's power, allowing developers to easily find and manipulate HTML elements. Next, you could learn about jQuery events, another crucial aspect of jQuery.

5. Practice Exercises

Here are some exercises to help you practice:

  1. Select all <div> elements with a class of "container" and change their border to 1px solid black.

Solution:

$(".container").css("border", "1px solid black");
  1. Select the element with the ID of "special" and change its font size to 24px.

Solution:

$("#special").css("font-size", "24px");
  1. Select all <p> elements inside a <div> and change their color to red.

Solution:

$("div p").css("color", "red");

For further practice, try manipulating different CSS properties of various elements using jQuery selectors.