Element Selection

$(selector) returns an array-like jQuery 561 set. It accepts CSS selectors plus jQuery extensions such as :header, :input, :checkbox, :visible and :contains(text). Expansion methods reach related elements: .find(), .children(), .parent(), .parents(), .closest(), .siblings(), .add(), .next(), .nextAll(), .nextUntil() and the .prev*() versions. Reduction methods narrow the set: .eq(i), .first(), .last(), .even(), .odd(), .slice(), .filter(), .not(), .has(). .end() returns to the previous set and .addBack() merges it in.

Expanding and reducing a jQuery setHTMLLive
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<pre id="log" style="margin:0"></pre>
<div hidden><span>1</span><span>2</span><p>A</p><p>B</p><p>C</p></div>
<script>
  for (const expr of ["$('div').children('p').add('span').length",
    "$('span').first().next().addBack().length", "$('p').eq(1).nextAll().text()",
    "$('p, span').not('p').last().text()", "$('p').index($('p:contains(C)'))"]) {
    $('#log').append(`${expr} -> ${new Function(`return ${expr}`)()}\n`);
  }
</script>
Browser output of Listing 8.61
Browser output of 61

Extensions such as :first and :contains() bypass the native querySelectorAll() (Selecting Elements), so prefer .first() in hot paths. An empty set never throws: $('#typo').hide() silently does nothing.