Episode 5 of 24
jQuery Selectors
Master jQuery selectors — the powerful way to find any element on the page.
jQuery selectors let you find and select HTML elements using the same syntax as CSS selectors. This is one of jQuery's greatest strengths.
Basic Selectors
$("p") // All <p> elements
$(".intro") // All elements with class "intro"
$("#main") // Element with id "main"
$("*") // All elements
Combining Selectors
$("h1, h2, h3") // All h1, h2, and h3 elements
$("div.container") // Divs with class "container"
$("ul li") // All li inside ul (descendant)
$("ul > li") // Direct child li of ul
$("h2 + p") // First p immediately after h2
Attribute Selectors
$("[href]") // Any element with href attribute
$("[type='text']") // Inputs with type="text"
$("a[target='_blank']") // Links that open in new tab
$("[data-role]") // Elements with data-role attribute
Practical Examples
// Highlight all paragraphs
$("p").css("background", "#ffe0b2");
// Hide all images inside a specific div
$(".gallery img").hide();
// Select nested elements
$("table tr td").css("padding", "10px");
// Change all external links
$("a[href^='http']").attr("target", "_blank");
Checking Selection
// How many elements were selected?
let count = $("p").length;
console.log("Found", count, "paragraphs");
// Does an element exist?
if ($("#sidebar").length) {
console.log("Sidebar exists!");
}