Children and Find

Move down the DOM tree to descendants.

Syntax$(selector).children(); $(selector).find(sel);

To go down the tree:

  • .children() — direct children only (one level down).
  • .find(selector) — all matching descendants at any depth.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A tab panel uses .children('.tab-pane') to hide all sibling panes and show only the selected one.
  • A search filter uses .find('li') deep inside a nested menu structure to hide non-matching items.
  • A form reset helper uses .find(':input') on a section to clear only the fields within that section.

More examples

Select direct children by class

.children() only descends one level, so the nested <li> inside the sub-menu is not affected.

Example · html
<ul id="menu">
  <li class="item">Home</li>
  <li class="item">About
    <ul>
      <li class="item">Team</li>
    </ul>
  </li>
</ul>
<button id="color">Color direct children</button>
<script>
$(function () {
  $("#color").click(function () {
    $("#menu").children(".item").css("color", "steelblue");
  });
});
</script>

Find a descendant at any depth

.find() searches all descendants at any depth, unlike .children() which stops after one level.

Example · html
<div id="container">
  <section>
    <p class="highlight">Found me!</p>
  </section>
</div>
<button id="find">Find p.highlight</button>
<script>
$(function () {
  $("#find").click(function () {
    $("#container").find("p.highlight").css("background", "yellow");
  });
});
</script>

Clear all inputs inside a section

.find(":input") locates all form controls nested anywhere inside the section and clears their values.

Example · html
<section id="personal">
  <input type="text" placeholder="First name" value="Alice" />
  <input type="email" placeholder="Email" value="[email protected]" />
</section>
<button id="clearSection">Clear section</button>
<script>
$(function () {
  $("#clearSection").click(function () {
    $("#personal").find(":input").val("");
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.