Q:

How to select an element with multiple classes with jQuery

0

How to select an element with multiple classes with jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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, as shown below:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Selecting Elements with Multiple Classes</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to loop through an array in JavaScript... >>
<< How to refresh a page with jQuery...