How to select child elements under id in jQuery

JqueryCss Selectors

Jquery Problem Overview


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 {}

Jquery Solutions


Solution 1 - Jquery

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:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionkvu787View Question on Stackoverflow
Solution 1 - JqueryDavid ThomasView Answer on Stackoverflow