In jquery, there are 2 ways to determine whether an element contains a deterministic class. The two methods have the same function. 2 methods are as follows:
1. Is ('. ClassName ')
2. Hasclass (' 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.