Example 2 — Text Nodes Do Not Block
Show that “Sibling!” text still allows a lone button to match.
var $box = $("#box-text");
var buttons = $box.children("button").length;
var only = $box.find("button:only-child").length;
console.log("button elements:", buttons);
console.log("only-child matches:", only);
console.log("text present:", $box.text().indexOf("Sibling!") !== -1);
button elements: 1
only-child matches: 1
text present: true
How It Works
- Count elements. Only one
button child exists. - Text is noise. “Sibling!” is a text node, not an element sibling.
- Match succeeds.
button:only-child still selects it.
Example 3 — Two Buttons → No Match
When two element siblings share a parent, neither is :only-child.
var $box = $("#box-pair");
console.log("buttons:", $box.find("button").length);
console.log("only-child:", $box.find("button:only-child").length);
console.log("first-child:", $box.find("button:first-child").length);
console.log("last-child:", $box.find("button:last-child").length);
buttons: 2
only-child: 0
first-child: 1
last-child: 1
How It Works
- Two element children. Official rule: nothing matches
:only-child. - First still works. One button is
:first-child. - Last still works. The other is
:last-child.