Getting Started

Selectors

Master jQuery selectors to target any element on the page with precision.

jQuery Selectors

jQuery selectors are based on CSS selectors — if you know CSS, you already know most of jQuery's selectors.

Basic Selectors

SelectorExampleSelects
Element$("p")All <p> elements
ID$("#myId")Element with id="myId"
Class$(".myClass")Elements with class="myClass"
All$("*")All elements
Multiple$("p, h1")All <p> and <h1>

Hierarchy Selectors

SelectorExampleSelects
Descendant$("div p")All <p> inside <div>
Child$("div > p")Direct <p> children of <div>
Adjacent$("h1 + p")First <p> immediately after <h1>

Filter Methods

Chain methods to narrow selections: .first(), .last(), .eq(n), .filter(), .not(), .find()

Example

javascript
// Basic selectors
$("p")           // all paragraphs
$("#header")     // element with id="header"
$(".btn")        // elements with class="btn"

// Attribute selectors
$("input[type='email']")   // email inputs
$("a[href^='https']")      // links starting with https
$("img[src$='.png']")      // images ending with .png

// Hierarchy
$("nav a")        // all links inside nav
$("ul > li")      // direct list items of ul
$(".card h2")     // h2 inside .card

// Filters
$("li:first")     // first li
$("li:last")      // last li
$("li:even")      // even-indexed li elements
$("li:odd")       // odd-indexed li elements
$("li:eq(2)")     // third li (0-indexed)
$("p:contains('Hello')")  // p tags containing "Hello"

// Traversal
$("#myList").find("li")           // find li inside #myList
$(".active").siblings()          // all siblings of .active
$(".child").parent()             // direct parent
$(".item").closest(".container") // nearest ancestor matching selector
$("h2").next()                   // next sibling
$("p").prev()                    // previous sibling

// Context
$("li", "#myList")  // li elements within #myList only

// Every selector above matches nothing, because this panel starts as a blank
// page — which is why running it printed nothing. Give them something to
// match, then print what they found:
$("#demo").append(
  '<ul id="myList">' +
    '<li>Alpha</li><li class="active">Beta</li><li>Gamma</li>' +
  '</ul>' +
  '<p>Hello world</p>'
);

console.log("li count:", $("#myList li").length);
console.log("first:", $("#myList li:first").text());
console.log("last:", $("#myList li:last").text());
console.log("even-indexed:", $("#myList li:even").map(function () {
  return $(this).text();
}).get());
console.log("the .active one:", $("#myList .active").text());
console.log("p:contains('Hello') matches:", $("p:contains('Hello')").length);
Try it yourself — JAVASCRIPT