Select All Elements Inside a Div with jQuery

Selecting all elements inside a specific div is a routine DOM manipulation task in jQuery. This article provides a quick guide to the primary methods used to target all descendant or direct child elements within a specific container, using standard selectors like the universal selector (*), the .find() method, and the .children() method.

1. Using the Universal Descendant Selector

The most direct way to select every element nested inside a specific div is by combining the container's ID or class with the CSS universal selector (*).

// Selects all descendants inside a div with the ID "myDiv"
$('#myDiv *');

This targets all descendant levels, including children, grandchildren, and deeply nested tags.

2. Using the .find() Method

If you already have a jQuery object representing your container or want to leverage method chaining, use the .find() method passed with the universal selector:

// Finds every descendant element inside #myDiv
$('#myDiv').find('*');

This approach performs the same selection as $('#myDiv *'), but it is often faster when working with previously cached jQuery selectors.

3. Selecting Direct Children Only

If you only want to select the immediate child elements and exclude deeper nested descendants, use the .children() method instead of the universal selector:

// Selects only direct children of #myDiv
$('#myDiv').children();

Practical Example

Given the following HTML structure:

<div id="container">
    <p>Paragraph <span>with nested text</span></p>
    <button>Click Me</button>
</div>

You can apply styles or classes to all elements inside #container like this:

// Add a CSS border to every element inside #container
$('#container').find('*').css('border', '1px solid red');

In this example, the <p>, <span>, and <button> elements will all receive the border styling.