Understanding the jQuery :only-child Selector
The jQuery :only-child selector identifies and selects
elements that are the sole child of their parent container. This article
covers how the selector evaluates target elements in the Document Object
Model (DOM), the precise conditions required for it to return a match,
and how it differs from similar structural pseudo-class selectors.
How the :only-child Selector Evaluates
The :only-child selector evaluates whether a targeted
element has zero sibling elements within its immediate parent. In
jQuery, writing $("selector:only-child") instructs the
engine to check every element matching selector and inspect
its parent.
The evaluation process follows these strict rules:
- True (Selected): The target element is the single, unique element node inside its parent element.
- False (Ignored): The parent element contains two or more child elements, meaning the target element shares the parent with at least one sibling.
Syntax
$("p:only-child")This query targets any <p> element that has no
siblings inside its parent.
Sibling Types and Evaluation Strictness
A critical aspect of how :only-child evaluates is its
relationship to sibling tag types. Unlike type-specific selectors,
:only-child considers all element siblings
regardless of their tag name.
Consider the following HTML snippet:
<div class="box">
<p>First paragraph</p>
<span>A descriptive label</span>
</div>If you run $("p:only-child"), the evaluation returns
false and selects nothing. Even though there is only
one <p> tag inside
<div class="box">, the <p> element
is not an only child because a <span> sibling
exists.
For an element to evaluate to true, the structure must
look like this:
<div class="box">
<p>Sole child paragraph</p>
</div>In this case, $("p:only-child") evaluates to
true and selects the paragraph.
Text Nodes and Comments
The :only-child selector follows standard CSS and DOM
specifications regarding nodes:
- HTML Comments: Comments
(
<!-- comment -->) are not element nodes and are ignored during evaluation. - Plain Text / Whitespace: Bare text nodes and whitespace inside the parent do not count as sibling elements.
As long as no other HTML element nodes share the parent, the target evaluates successfully.
Difference Between :only-child and :only-of-type
Developers often confuse :only-child with
:only-of-type:
:only-child: Requires the element to be the only HTML element child of its parent, with no other elements of any kind present.:only-of-type: Requires the element to be the only child of its specific tag type inside the parent, regardless of how many other different HTML elements are present.