jQuery select by class

Filed Under: jQuery

jQuery select by class name allows us to find a specific HTML element with the value of its class attribute.

jQuery select by class

Here is the general syntax for using the jQuery select by class name:

$(".classname")

ID could be any value provided in the id attributes of the HTML element. You should use period character ( .) followed by the class name specified in the html element.

$(".myClass"): This will select all HTML elements with class name equal to “myClass”.

For example if there is a HTML element in the document like <div class="myClass"> some text </div>, $(“.myClass”) will select this div and do the intended action on it. All the manipulations will affect only the elements specified with the given class name in the selector.

jQuery select by class example

This example demonstrates the use of jQuery select by its class name and changing the CSS style of the selected element.


<html>
<head>
<title>jQuery select by Class</title>

<style>
div, span {
width: 130px;
height: 50px;
float: left;
padding: 15px;
margin: 15px;
background-color: #EEEEEE;
}
</style>

<script src="//code.jquery.com/jquery-3.2.1.js"></script>

</head>
<body>
<div class="class1">div element className="class1"</div>
<div class="class2">div element className="class2"</div>
<span class="class3">span element className="class3"</span>
<script>
$( ".class2" ).css( "border", "5px solid green" );
</script>
</body>
</html>

You can see that <div> element with class=”class2″ is selected for manipulation and some other styles are added to it.

Below image shows the output page rendered by the browser.

jquery select by class

jQuery Select by Class Demo

jQuery select by class summary

jQuery class selector makes it easy to apply CSS class to any number of elements in the html document. This selector is very helpful in keeping uniformity of certain elements.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages