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 httpsFiltering
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/radiosTraversal
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 selectorChaining
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.