Home > Article > Web Front-end > jquery adds class to element
jQuery is a widely used JavaScript library that simplifies HTML document traversal and manipulation, event handling, animation effects, and Ajax operations. One of the common operations is to add a class to an element.
Classes are used to define styles in HTML and can control the appearance of elements. Adding a class allows developers to update styles without changing other properties of the element. For example, if a button needs to change color after being clicked, this can be achieved by adding a class to it.
In jQuery, you can add classes to elements through the addClass()
method. This method accepts one or more class names as parameters, separated by spaces. If the element already has a class, the addClass()
method will not add this class repeatedly.
The following is a simple example. After clicking the button, add the red
class to the <div>
element:
<!DOCTYPE html> <html> <head> <title>Add Class Demo</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <style> .red { background-color: red; } </style> </head> <body> <button id="add-class">Add Class</button> <div id="target">This is a div.</div> <script> $(function() { $('#add-class').on('click', function() { $('#target').addClass('red'); }); }); </script> </body> </html>
First, define a red
class, set the background color to red. Then, add a button and a <div>
element in the HTML, and set ids to them respectively. In JavaScript, the click event of the button is bound. When the button is clicked, the <div>
element is selected through the selector and the addClass()
method is called to add # to it. ##redClass.
style attribute to directly modify the style of an element, it may overwrite the previously set style or affect other styles. The method of adding a class will only apply the style of the newly added class and will not affect other styles.
data-* in HTML5 can select elements through CSS selectors and jQuery selectors, and add special styles or interactive behaviors to elements.
The above is the detailed content of jquery adds class to element. For more information, please follow other related articles on the PHP Chinese website!