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

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.