jQuery Selectors

Selectors find elements in the DOM. jQuery uses CSS selectors plus extras.

Basic Selectors

JavaScript
$('p')                 // all <p> elements
$('p.intro')           // <p> with class="intro"
$('#header')           // element with id="header"
$('[type="text"]')     // elements with type="text"
$('ul > li')           // <li> direct children of <ul>
$('a[href^="https"]')  // links starting with https

Filtering

JavaScript
$('p').first()           // first <p>
$('p').last()            // last <p>
$('p').eq(2)             // third <p> (0-indexed)
$('p').filter('.active') // <p> with class="active"
$('p').not('.hidden')    // <p> without class="hidden"
$('div:has(p)')          // <div> containing a <p>
$('input:checked')       // checked checkboxes/radios

Traversal

JavaScript
$('li').parent()       // parent of each <li>
$('li').children()     // direct children
$('li').find('span')   // all <span> descendants
$('li').next()         // next sibling
$('li').prev()         // previous sibling
$('li').siblings()     // all siblings
$('li').closest('ul')  // nearest ancestor matching selector

Chaining

JavaScript
$('ul')
  .find('li')
  .first()
  .addClass('highlight')
  .css('color', 'red');

Tips

  • Use event delegation for dynamic content.
  • Chain methods for readable code.
  • Use .filter() and .not() for complex selection.

Next: events.