When you use jQuery, the first step is usually to tell it what part of your webpage you want to work with. That’s where selectors come in!
Think of jQuery selectors like pointing your finger at something on the page and saying, “Hey jQuery, do something with this!”
What Is a jQuery Selector?
A selector lets jQuery "select" or "find" HTML elements (like buttons, text, images) so you can add styles, change content, or respond to events.
The basic syntax looks like this:
$(selector).action();
-
selector: the thing you want to select (like a button or paragraph)
-
action(): what you want to do to it (like hide, change color, etc.)
Common Selectors (Super Easy!)
1. ID Selector
Use # to select something by ID:
$("#myButton").hide();
This hides the element with the ID myButton.
2. Class Selector
Use . to select something by class:
$(".highlight").css("color", "red");
This changes the text color of everything with the class highlight to red.
3. Element Selector
Just type the name of the HTML tag:
$("p").fadeOut();
This fades out all <p> (paragraph) elements on the page.
You Can Combine Selectors!
$("h1, p").hide();
$("div.box").slideUp();
$("#logo.main").css("border", "2px solid blue");
Quick Practice:
Guess what this does?
$(".btn").click(function() {
$("h1").text("Hello, world!");
});
Answer: When any element with class btn is clicked, the text in all <h1> elements changes to "Hello, world!"
Final Tips
$(document).ready(function() {
// Your jQuery code goes here
});