How to select elements with multiple classes in jQuery
Overview
In jQuery, we can select elements with multiple classes using the .class selector.
Syntax
All the classes that are to be selected are specified as below.
$('.class1.class2.class3...')
Syntax of class selector
Example
Explanation
In the HTML tab:
- Line 5: We create a div with
id=content. - Lines 6–10: We create five
pelements withclass=line.
Note: We added the
showclass to the third and fifthpelement.
- Line 12: We create a button
Highlight. - Line 14: We import the
jQueryscript.
In the JavaScript tab:
- Line 3: We attach the
click()method on theHighlightbutton. - Line 5: We use the
.classselector to select all the elements with classeslineandshow. Also, we use thetoggleClass()method to toggle classhighlight.
Output
- When the
Highlightbutton is clicked, all the elements with classeslineandshoware selected. - The background color of the selected items is toggled.