Examples of addClass () method usage in jQuery, jqueryaddclass
This document describes the addClass () method usage in jQuery. Share it with you for your reference. The specific analysis is as follows:
This method adds one or more classes to the matching element.
This method has multiple syntax forms.
Syntax structure 1:
Add the specified class name to the matching element. If you want to add multiple class names at a time, they must be separated by spaces.
Copy codeThe Code is as follows: $ (selector). addClass (class)
Parameter List:
| Parameters |
Description |
| Class |
Define the name of the added class |
Instance code:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8">
<Meta name = "author" content = "http://www.bkjia.com/"/>
<Title> addClass function-helper's house </title>
<Style type = "text/css">
Div {
Height: 200px;
Width: 200px;
}
. Border {
Border: 1px solid red;
}
. Reset {
Font-size: 20px;
Color: green;
}
</Style>
<Script type = "text/javascript" src = "mytest/jQuery/jquery-1.8.3.js"> </script>
<Script type = "text/javascript">
$ (Document). ready (function (){
$ ("# Btn"). click (function (){
$ ("Div"). addClass ("border reset ");
})
})
</Script>
</Head>
<Body>
<Div> welcome to helper's house </div>
<Button id = "btn"> click to view results </button>
</Body>
</Html>
The code above can add two classes for the div, which can set the border and Font Style of the div.
Syntax structure 2:
Use the return value of the function as the name of the class to be added.
Copy codeThe Code is as follows: $ (selector). addClass (function (index, oldclass ))
Parameter List:
| Parameters |
Description |
| Function (index, oldclass) |
The Function Definition returns one or more class names to be added. Index-(optional) index location of the selector. Oldclass-(optional) Name of the current class that accepts the selector. |
Instance code:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8">
<Meta name = "author" content = "http://www.bkjia.com/"/>
<Title> addClass () function-helper's house </title>
<Style type = "text/css">
Div {
Height: 200px;
Width: 200px;
}
. Border {
Border: 1px solid red;
}
. Reset {
Font-size: 20px;
Color: green;
}
</Style>
<Script type = "text/javascript" src = "mytest/jQuery/jquery-1.8.3.js"> </script>
<Script type = "text/javascript">
$ (Document). ready (function (){
$ ("# Btn"). click (function (){
$ ("Div"). addClass (function (){
Return "border reset ";
})
})
})
</Script>
</Head>
<Body>
<Div> welcome to helper's house </div>
<Button id = "btn"> click to view results </button>
</Body>
</Html>
The code above is the same as the function of the first instance, except that the class to be added is obtained through the function return value.
I hope this article will help you with jQuery programming.