Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

jquery
communitycreator
class selector

How to select elements with multiple classes in jQuery

Shubham Singh Kshatriya

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 p elements with class=line.

Note: We added the show class to the third and fifth p element.

  • Line 12: We create a button Highlight.
  • Line 14: We import the jQuery script.

In the JavaScript tab:

  • Line 3: We attach the click() method on the Highlight button.
  • Line 5: We use the .class selector to select all the elements with classes line and show. Also, we use the toggleClass() method to toggle class highlight.

Output

  • When the Highlight button is clicked, all the elements with classes line and show are selected.
  • The background color of the selected items is toggled.

RELATED TAGS

jquery
communitycreator
class selector

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring