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 wasa 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