jQuery :first-child Selector
The jQuery :first-child Selector is used to select every element that is the first child of its parent element.
Syntax:
$("Selector:first-child")
It selects and returns the first child element of its parent element.
Example 1: In this example, we select the first paragraph element and set its background color to green.
HTML
<!DOCTYPE html> < html > < h1 > < center >Geeks</ center > </ h1 > < head > < script src = </ script > < script > $(document).ready(function () { $("p:first-child").css( "background-color", "green"); }); </ script > </ head > < body > < div > < p >Geeks for Geeks</ p > < p >jQuery</ p > < p >First Child Selector</ p > </ div > </ body > </ html > |
Output:
Example 2:
HTML
<!DOCTYPE html> < html > < h1 > < center >Geeks</ center > </ h1 > < head > < script src = </ script > < script > $(document).ready(function () { $("p:first-child").css( "background-color", "green"); }); </ script > </ head > < body > < div style = "border:1px solid;" > < p >Geeks for Geeks</ p > < p >jQuery</ p > </ div > < br > < div style = "border:1px solid;" > < p >Geeks for Geeks</ p > < p >jQuery</ p > < p >First Child Selector</ p > </ div > < div >jQuery:First Child Selector</ div > </ body > </ html > |
Output:
Supported Browsers:
- Google Chrome 90.0+
- Internet Explorer 9.0
- Firefox 3.6
- Safari 4.0
- Opera 10.5
Please Login to comment...