jQuery first()
0 1322
- This jQuery method is used to fetch the first element of the selected HTML elements.
- This jQuery method is used in filtering the desired elements with jQuery.
- To return the last element of the selected HTML element, use last() jQuery method.
Related Topics:
jQuery next
jQuery prev
jQuery first
Syntax:
$(selector).first() ;
This jQuery method has no parameter
Example 1
In this example we select the first heading of div element.
<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
div{
background:pink;
padding:10px;
margin:10px;
font-size:20px;
}
h3{
padding:10px;
margin:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div h3").first().css({"border":"3px solid green","background":"yellow"});
});
});
</script>
</head>
<body>
<h2> jQuery first() method Example </h2>
<div>
<h3> This is the first heading of div element </h3>
<h3> This is the second heading of div element </h3>
<h3> This is the last heading of div element </h3>
</div>
<button> Click Me! </button>
</body>
</html>
Output:
When you click the button,
Example 2
In this example, we select the first heading of first div element.
<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
div{
background:pink;
padding:10px;
margin:10px;
font-size:20px;
}
h3{
padding:10px;
margin:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div h3").first().css({"border":"3px solid green","background":"yellow"});
});
});
</script>
</head>
<body>
<h2> jQuery first() method Example </h2>
<div>
<h3> This is the first heading of first div element </h3>
<h3> This is the second heading of first div element </h3>
</div>
<div>
<h3> This is the first heading of second div element </h3>
<h3> This is the second heading of second div element </h3>
</div>
<button> Click Me! </button>
</body>
</html>
Output:
When you click the button,
Share:
Comments
Waiting for your comments