How to use jquery to determine whether an element contains a specified class

Source: Internet
Author: User

In jquery, there are 2 ways to determine whether an element contains a deterministic class. The two methods have the same function. There are 2 ways to do this: (individuals prefer to use hasclass ())

1. Hasclass (' classname ')

2. Is ('. ClassName ')

The following is an example of whether a DIV element contains a redcolor:

1. Using the IS ('. ClassName ') method
$ (' div '). is ('. Redcolor ')
2. Use Hasclass (' classname ') method (note that the lower version of jquery may be hasclass ('. ClassName '))
$ (' div '). Hasclass (' Redcolor ')

The following is an example that detects whether an element contains a Redcolor class and, when contained, changes its class to Bluecolor.

<HTML>
<head>
<styletype= "Text/css" >
background:red;
}
Background:blue;
}
</Style>
<scripttype= "Text/javascript" src= "jquery-1.3.2.min.js" ></script>
</Head>
<body>
<H1>jquery Check if an element has a certain class</H1>
<divclass= "Redcolor" >this is a div tag with class name of "Redcolor" </div>
<P>
<buttonid= "Istest" >is ('. Redcolor ') </button>
<buttonid= "Hasclasstest" >hasclass ('. Redcolor ') </button>
<buttonid= "reset" >reset</button>
</P>
<scripttype= "Text/javascript" >
$ ("#isTest"). Click (function () {
if ($ (' div '). is ('. Redcolor ')) {
$ (' div '). addclass (' Bluecolor ');
}
});
$ ("#hasClassTest"). Click (function () {
if ($ (' div '). Hasclass (' Redcolor ')) {
$ (' div '). addclass (' Bluecolor ');
}
});
$ ("#reset"). Click (function () {
Location.reload ();
});
</Script>
</Body>
</HTML>

Initial effect:

Effect after clicking on is ('. Redcolor '):

Clicking on the Hasclass (' Redcolor ') effect is the same as clicking on the IS ('. Redcolor ') and clicking Reset is the same as the original effect.

How to use jquery to determine whether an element contains a specified class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.