SyntaxStudy
Sign Up
jQuery jQuery Children and Descendant Traversal
jQuery Beginner 4 min read

jQuery Children and Descendant Traversal

Traversing downward — from a container to its nested elements — is used whenever you need to interact with the contents of an element found by a prior traversal or event. jQuery provides two main downward traversal methods with an important distinction between them.

.children()

.children() returns only the direct children of each matched element — one level down. An optional selector filters the results. It never descends further than immediate children, making it fast and predictable for well-structured markup.

.find()

.find(selector) searches all descendants at any depth. It is the traversal equivalent of a scoped $(selector, context) call. Always prefer .find() over $('#parent .child') when you already hold a jQuery reference to the parent, as it avoids rescanning the entire document.

  • .children() — direct children only
  • .find(selector) — all descendants matching selector
  • .contents() — all child nodes including text nodes and comments

For performance in large DOMs, always scope .find() to the smallest practical container. A .find() on $('body') is essentially the same as a global selector, defeating the purpose of scoping.

Example
// Direct children only
var $listItems = $('#nav > ul').children('li');
console.log('Top-level nav items:', $listItems.length);

// All descendants
$('#data-table').find('td.error').addClass('highlight');

// Scoped find vs global selector
var $form   = $('#order-form');
var $inputs = $form.find('input, select, textarea');
$inputs.on('change', validateField);

// Children with filter
$('#gallery').children('img:visible').each(function () {
    $(this).attr('loading', 'lazy');
});

// .contents() — includes text nodes
$('p').contents().filter(function () {
    return this.nodeType === 3; // text nodes
}).wrap('<span class="text-node"></span>');
Pro Tip

Always prefer $parent.find(selector) over a global $(selector) — it limits the search to the subtree and is faster.