jQuery class | How to use class attribute of an HTML element with jquery class selector

HTML Classes

In your web projects, the presentation layer or HTML may contain classes. For example in DIV, or paragraphs, links and others 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 Class selector. The syntax is as follows:

Syntax of jQuery class name selector

$(“.class”);

Example

Selecting elements by class names requires calling by ‘.’ (period) followed by class name of the element. The jquery selector will search for given class in document and perform given action.

$(“myDivclass”).show;

$(“myPclass”).hide;

Example of Selector by .Class name

The example below is the basic but it explains proper class formatting and then using it in jquery element selector. Internal CSS is used to create classes placed in<head> section. Normally you might use external CSS.

When Green Text is clicked it will show only green text and hide red and orange <p>, when red text is clicked then only red will display while orange and green will be hidden by using jquery hide() method. Save below code in jquerytest.html file or whatever and run it in browser. Note that jquery library is included from Google CDN, so you don’t need to download and refer its physical path.



Also see: jquery removeclass() method


Was this article helpful?

Related Articles

Leave A Comment?