JQuery is a widely used JavaScript library that allows users to operate on HTML elements. One common operation is to obtain the class name or class value of an element. In this article, we will introduce how to get the value of class using JQuery.
Getting the value of class
Getting the value of class is very simple. You only need to use a built-in function in JQuery - attr()
. This function can get the attribute value of an HTML element. For classes, just pass the class as a parameter to the function. For example, the following code will get the class value of the div named "example":
var className = $('div.example').attr('class');
In the above code, $ is the alias of JQuery, and div.example means matching all divs named "example" in HTML div element. Therefore, className will store the class value of the div named "example".
In addition, if you want to check whether an element contains a specific class, you can use the hasClass()
function. For example, the following code will check whether the div element named "example" contains the "highlight" class:
if ($('div.example').hasClass('highlight')) { // do something }
In the above code, if the div named "example" contains highlight, the if code in the statement.
Summary
The above are two simple methods to use JQuery to get the class value. Basically, you only need to remember attr()
and hasClass()
With these two functions, you can quickly and easily obtain and check the class of HTML elements. In actual development, obtaining class values is a task that often needs to be done, so mastering JQuery can save a lot of time and energy.
The above is the detailed content of How to get the value of class in jquery. For more information, please follow other related articles on the PHP Chinese website!