How to select an element with multiple classes with jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Specify Class Names without Spaces in Between

If you want to target the elements with multiple classes names, such as selecting the elements only if it has both classA and classB, or has classes classA, classB,...,classX or something like that, just put the class selectors together without any space in between, like this:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery Selecting Elements with Multiple Classes</title>
  • <script src=""></script>
  • <script type="text/javascript">
  •     $(document).ready(function(){
  •         // Apply background color to the elements if it has both classA and classB
  •         $(".classA.classB").css("background-color", "yellow");
  •     });
  • </script>
  • </head>
  • <body>
  •     <p class="classA">Element with classA (won't match)</p>
  •     <p class="classA classB">Element with classA and classB (match)</p>
  •     <p class="classB">Element with classB (won't match)</p>
  •     <p class="classB classA">Element with classB and classA (match)</p>
  •     <p class="classD">Element with classD (won't match)</p>
  •     <p class="classA classD classB">Element with classA, classD and classB (match)</p>
  • </body> 
  • </html>

See the tutorial on jQuery selectors to learn more about selecting elements in jQuery.

Related FAQ

Here are some more FAQ related to this topic:


Your Feedback:


We would love to hear from you! Please say something.