How to select child elements under id in jQuery

Sample code:

<div id='container'>
  <h1>heading 1</h1>
  <h2>heading 2</h2>
  <p>paragraph</p>
</div>

I would like a jQuery equivalent of this CSS selector to select the h1 element under the div:

#container h1 {}

You can simply implement the exact same selector:

$('#container h1')

Which selects every h1 element found within the #container element, or:

$('#container > h1')

Which selects only those h1 elements that have the #container element as their parent (not grandparent, or other form of ancestor).

Or, if you prefer:

$('#container').find('h1')

You could also restrict it to a particular h1 element:

$('#container h1:first')

Which selects only the first h1 element within the #container element.

References:

  • find().
  • :first selector.
  • jQuery selectors.