Select first element with the given class name in jQuery
In this tutorial, you will learn how to select the first element with given class name using jQuery.
Solution
To select the first element in the document with given class name using jQuery, you can use the class selector in combination with the :first
pseudo-selector.
var elements = $("classname:first");
where you can replace the classname
with the class name of required elements. For example, if you would like to get the first element of those which has a class name of my-class-1
in the document, you can use the ".my-class-1:first"
selector.
Programs
1. In the following script, when user clicks on the button, we select the first element with the class name my-class-1
in the document, and change its color to red.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#action").click(function() {
// Select the first element with given class name
var element = $(".my-class-1:first");
// Do something with the selected element
element.css("color", "red");
});
});
</script>
</head>
<body>
<h2>Hello User!</h2>
<input type="submit" id="action" value="Click Me"></input>
<p>This is a paragraph.</p>
<p class="my-class-1">This is second paragraph.</p>
<p class="my-class-1">This is third paragraph.</p>
<h3>Another section</h3>
</body>
</html>