Select all elements with specific class name in jQuery
In this tutorial, you will learn how to select all the elements with specific class name using jQuery.
Solution
To select all the elements in the document that have specific class name using jQuery, use the .
selector followed by the class name, as shown in the following.
var elements = $(".my-class");
Programs
1. In the following script, when user clicks on the button, we select all the elements in the document which has a class name of my-note
, and change their 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 elements by classname
var elements = $(".my-note");
// Do something with the selected elements
elements.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-note">This is second paragraph.</p>
<p class="my-note">This is third paragraph.</p>
</body>
</html>