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>
<head>
<title>jQuery :first-child Selector</title>
<script src=
</script>
<script>
$(document).ready(function () {
$("p:first-child").css(
"background-color", "green");
});
</script>
</head>
<body>
<h1>
<center>Geeks</center>
</h1>
<div>
<p>Geeks for Geeks</p>
<p>jQuery</p>
<p>First Child Selector</p>
</div>
</body>
</html>
|
Output:

Example 2:Â The below example shows how the first child <p> will be selected of two different div elements and styled using jQuery.
HTML
<!DOCTYPE html>
<html>
<head>
<title>jQuery :first-child Selector</title>
<script src=
</script>
<script>
$(document).ready(function () {
$("p:first-child").css(
"background-color", "green");
});
</script>
</head>
<body>
<h1>
<center>Geeks</center>
</h1>
<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
Last Updated :
14 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...