Home > Web Front-end > JS Tutorial > body text

How to modify the element class name by clicking in jquery

WBOY
Release: 2021-11-22 17:08:42
Original
3194 people have browsed it

jquery implements the method of clicking to modify the class name of an element: 1. Bind the click event to the element and specify an event processing function; 2. Use the attr() method in the event processing function to modify the class name of the element. , the syntax is "$(selector).attr('class','new class name');".

How to modify the element class name by clicking in jquery

The operating environment of this tutorial: windows7 system, jquery1.10.0 version, Dell G3 computer.

How jquery implements clicking to modify the element class name

1. Create a new html page with the file name test.html, which is used to implement the operation. The function of the div element. Load the jquery.min.js file in the html page. This file integrates all methods of jquery. Only when the file is successfully loaded can the methods in jquery be used. Create a new div element on the html page and give it a class name red.

In order to achieve obvious effects after clicking, the background color of the div with class="red" is defined as red through CSS, and when the class name is black, the background color is black.

How to modify the element class name by clicking in jquery

2. Add an onclick event to the div element. When the onclick event is triggered, execute the change_color() method. This method is mainly used to change the class of the div.

Write the code to change the class of the div element in change_color(), so that when the div is clicked, class="red" changes to class="black" to realize the function of changing the class name. Mainly through the attr() method in jquery, the class name of the class is changed.

How to modify the element class name by clicking in jquery

Run the code and view the results in the browser:

How to modify the element class name by clicking in jquery

How to modify the element class name by clicking in jquery

is visible , realizes the function of clicking the div to change the class name.

Recommended related video tutorials: jQuery video tutorial

The above is the detailed content of How to modify the element class name by clicking in jquery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template