Home  >  Article  >  Web Front-end  >  How to determine whether a class exists in jquery

How to determine whether a class exists in jquery

coldplay.xixi
coldplay.xixiOriginal
2020-11-24 14:24:419209browse

How to determine whether a class exists in jquery: 1. Use the [is('.classname')] method; 2. Use the [hasClass('classname')] method, the code is [$('div' ).hasClass('redColor')].

How to determine whether a class exists in jquery

The operating environment of this tutorial: windows7 system, jquery3.2.1 version. This method is suitable for all brands of computers.

Methods for whether class exists in jquery:

There are two methods you can use in jquery to determine whether an element contains a certain class (class). Both methods have the same functionality. The 2 methods are as follows:

  • is('.classname')

  • hasClass('classname')

The following is an example of whether a div element contains a redColor:

1. Use 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 of detecting whether an element contains a redColor class, When included, change its class to blueColor.




.redColor {
background:red;
}
.blueColor {
background:blue;
}



jQuery check if an element has a certain class

This is a div tag with class name of "redColor"

is('.redColor') hasClass('.redColor') reset

$("#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(); });

Related free learning recommendations: JavaScript (video)

The above is the detailed content of How to determine whether a class exists in jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to delete select option in jQuery?Next article:How to delete select option in jQuery?

Related articles

See more