:only-child
S2C Home « Selectors « :only-child
Only child selector.
Shorthand version $(':only-child')
Description
The (':only-child')
selector, selects all elements that are the only child of the specified parent.
- Nodes with siblings will not be selected.
- If this selector is not preceded by another selector the universal selector ("*") is implied and so the whole DOM will be searched. Use another selector as in the examples below to narrow the search and improve performance.
Syntax
Signature | Description |
---|---|
jQuery(':only-child') | Only child match |
Parameters
None.
Return
N/A.
:only-child
ExamplesTop
Selects all elements that are the only child of the specified parent.
The following example will select 'i' elements that are the only children of 'p' elements and change the background colour of these elements to orange.
$(function(){
$('#btn1').on('click', function() {
$('p i:only-child').css('backgroundColor', 'orange');
});
});
The following example will select 'a' elements that are the only children of 'p' elements and change the background colour of these elements to silver.
$(function(){
$('#btn2').on('click', function() {
$('h4 span:only-child').css('backgroundColor', 'silver');
});
});
The following example will select the 'a' elements that are the only children of 'p' elements and change the background colour of these elements to yellow.
$(function(){
$('#btn3').on('click', function() {
$('p a:only-child').css('backgroundColor', 'yellow');
});
});