Learn to use jQuery class selector with HTML elements

jQuery Class with HTML elements

In your web projects, the presentation layer or HTML may contain classes. For example, in DIV, paragraphs, links and others you may use classes to format HTML elements. e.g.

  • <div class=”myDivclass”>
  • <p class=”myPclass”>
  • <a class=”myAclass”>

In order to perform actions on these elements on the basis of class attribute, jQuery provides the Class selector.

Syntax of class name selector

Following is the syntax of class selector:


Selecting the elements by class names require it calling by a ‘.’ (period) followed by the class name used in the element. The jQuery class selector will search for the given class in the document and perform the desired action.

For example:



Class Selector example

The following is a basic example that explains class formatting and then using it in the class element selector. The internal CSS is used to create the classes that are placed in the <head> section. Normally, you may want to use the external CSS.

In the example, as Green Text is clicked it will show only the green text and hides the red and orange <p> (paragraphs) by using the class selector. When the red text is clicked, only red will display while orange and green will be hidden by using the jQuery hide() method.

Save the following code in the jquerytest.html file or some other name of your choice and run it in your browser. Note that, the jQuery library is included from the Google CDN, so you don’t need to download and refer its physical path.

Experience this online

Experience this online

Also see: jQuery removeclass() method