:first-child
JQ Home <<
Selectors <<
:first-child
First child selector.
Shorthand version $(':first-child')
Description
The (':first-child')
selector, selects all first child elements of their parent.
- 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(':first-child') | First child match |
Parameters
None.
Return
N/A.
:first-child
Examples
Selectors << Top
Selects all first child elements of their parent.
The following example will select the first 'code' elements within 'p' elements and change the text colour of these elements to red (above and below Description heading).
$(function(){
$('#btn1').on('click', function() {
$('p code:first-child').css('color', 'red');
});
});
The following example will select the first 'span' elements within 'b' elements and change the background colour of these elements to orange.
$(function(){
$('#btn2').on('click', function() {
$('b span:first-child').css('backgroundColor', 'orange');
});
});
The following example will select the first 'a' elements within 'h3' elements and change the background colour of these elements to yellow (h3 headings in left sidebar).
$(function(){
$('#btn3').on('click', function() {
$('h3 a:first-child').css('backgroundColor', 'yellow');
});
});
Related Tutorials
jQuery Basic Tutorials - Lesson 3 - CSS Selectors