jQuery
jQuery Select Multiple Classes Examples
While dealing with CSS styles using jQuery, it might be desirable at times to make changes as per the requirements. And one of the requirement may be to select multiple classes. So in this article, I am going to share easy ways to use jQuery to select multiple classes. Read on to find out more.
How to use jQuery to Select Multiple Classes – Examples
Let’s say you have multiple classes called: “class1”, “class2” and “my_class”. If you want to target the elements that has all these classes applied to it, you can do it the following way:$('.class1 .class2 .my_class')If you want to select an element by using it’s ID without specifying it’s class and at the same time, use the classes for finding other elements, you can do it the following way:
$('.class1 .class2 .my_class #my_input_box')Example: Remove Blue class from all Divs that have Orange Class and Green Class applied to them
<style type="text/css">
.green {
color: #009900;
}
.blue {
background-color: #DFF2FF;
}
.red {
color: #D70000;
font-weight: bold;
}
.orange {
border: 10px solid #F90;
font-size: 200%;
font-weight:bold;
font-family: Georgia, "Times New Roman", Times, serif;
font-style: italic;
}
#my_div3 {
padding: 10px;
}
</style>
<div id="my_div1" class="orange green blue">This is MY DIV 1</div>
<br>
<div id="my_div2" class="orange green red blue">This is MY DIV 2</div>
<br>
<div id="my_div3" class="blue red">This is MY DIV 3</div>
<input type="submit" name="sbt_remove_class" id="sbt_remove_class" value="Remove Blue Class from all DIVs containing Orange Class and Green Class">
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
//This will add class to the a div that does NOT have any class applied to it already
$('#sbt_remove_class').on("click", function(e){
$('.orange, .green').removeClass('blue');
e.preventDefault();
});
});
</script>Simple isn’t it?
Do you know of any other ways to use jQuery to select multiple classes? Feel free to share your thoughts by commenting below.