jQuery :first-child Selector
The :first-child selector allows you to select the first child of its parent element which makes manipulating DOM elements efficient. In this article, we will explore the jQuery :first-child selector, how to use it, and provide practical examples.
What is the jQuery :first-child Selector?
The :first-child selector in jQuery is used to target and manipulate the first child element within a parent container. It helps in cases where you want to apply styles or make changes to the very first element of a group, like the first <p> (paragraph), <li> (list item), or <div> (division).
Syntax:
$("selector:first-child")
- selector: Specifies the HTML element you want to target.
- :first-child: Ensures that only the first child of the selected parent is manipulated.
Examples of jQuery :first-child Selector
Example 1: Selecting the First Paragraph Element
In this example, we will use jQuery to select the first paragraph (<p>) within a container and change its background color to green. This is a simple demonstration of how the :first-child selector works.
<!DOCTYPE html>
<html>
<head>
<title>jQuery :first-child Selector</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</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: Selecting the First Paragraph in Different Divs
Let’s see how to use the :first-child selector with multiple parent elements. In this case, we have two different <div> elements, each containing multiple paragraphs. We’ll apply the style only to the first child paragraph in both divs.
<!DOCTYPE html>
<html>
<head>
<title>jQuery :first-child Selector</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</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