Switching element classes means adding and removing specific classes from HTML elements based on specific conditions.
For example, we want to highlight an HTML div element when the mouse enters, we need to add a specific class with different styles in the HTML element.
Here we will learn various ways to switch element classes using JavaScript and jQuery. In this tutorial, we will learn to switch element classes in JavaScript.
Use the toggle() method of classList
toggle() method switches the class in the element. It checks if the class exists and then removes the class; otherwise, it adds the class to the element.
grammar
Users can use the toggle() method to switch element classes through JavaScript according to the following syntax.
divElement.classList.toggle("class_name");
In the above syntax, divElement is an HTML element in which we want to toggle the class passed as argument to the toggle method.
Example 1
In the example below, we create a div element and give it some styles. When the user clicks the button, it calls the toggleClass() function. In the toggleClass() function, we access the div element using its id.
After that, we apply the toggle() method to the classList of the div element. The classList property returns the classes of all div elements in array format. Additionally, we passed the "color" class name as a parameter to the toggle() method. So it will add and remove color classes in div elements.
<html> <head> <style> div { width: 10rem; height: 10rem; border: 2px solid blue; border-radius: 12px; } .color { background-color: grey; } </style> </head> <body> <h2 id="Using-the-i-toggle-method-i-to-toggle-and-element-class-using-JavaScript">Using the <i> toggle() method </i> to toggle and element class using JavaScript.</h2> <h3 id="Click-the-below-button-to-add-and-remove-the-class-from-the-below-div">Click the below button to add and remove the class from the below div.</h3> <div id="div-ele"></div> <br> <button onClick="toggleClass()">Toggle color class</button> <script> function toggleClass() { let divElement = document.getElementById('div-ele'); divElement.classList.toggle("color"); } </script> </body> </html>
In the above output, the user can observe that when we click on the button, it changes the background color of the div element as it switches the color category of the div element.
Use contains(), add() and remove() methods
contains method checks whether an array contains a specific element. The add() method adds a class to an element, and the remove() method removes a class from an element.
We can use the classList attribute to get all the classes contained by the element, and then we can use the contains() method to check whether the element contains a specific class. If it is not included we can add it; otherwise, we need to remove the class.
grammar
Users can use the contains(), add() and remove() methods according to the following syntax to switch the class of an element.
if (divElement.classList.contains("class_name")) { divElement.classList.remove("circle"); } else { divElement.classList.add("circle"); }
In the above syntax, we use the contains() method to check whether the classList contains the class_name class and based on this, we add and remove the class from the element.
Example 2
In the example below, we give some styles to the div element. Additionally, we created the "circle" class, which converts a div into a circle. Whenever the user clicks the button, the toggleClass() function checks whether the div element contains the "circle" class. If the contains() method returns true for the Circle class, we will remove the Circle class from the div using the remove() method with classList. Otherwise, we add the "circle" class in the div element using the add() method.
<html> <head> <style> div { width: 10rem; height: 10rem; border: 2px solid yellow; background-color: blue; display: flex; justify-content: center; align-items: center; color: white; font-size: larger; } .circle { border-radius: 50%; } </style> </head> <body> <h2 id="Using-the-i-contains-add-and-remove-method-i-to-toggle-and-element-class-using-JavaScript">Using the <i> contains(), add(), and remove() method </i> to toggle and element class using JavaScript. </h2> <h3 id="Click-the-below-button-to-add-and-remove-the-circle-class-from-the-below-div">Click the below button to add and remove the circle class from the below div. </h3> <div id="div-ele"> Square </div> <br> <button onClick="toggleClass()">Toggle color class</button> <script> function toggleClass() { let divElement = document.getElementById('div-ele'); let allClass = divElement.classList; // if the element contains the circle class, remove it; Otherwise, add it. if (allClass.contains("circle")) { divElement.classList.remove("circle"); divElement.innerHTML = "Square"; } else { divElement.classList.add("circle"); divElement.innerHTML = "Circle"; } } </script> </body> </html>
In the above output, the user can observe the div switching between round and square just by clicking the button.
Use JQuery’s toggleClass() method
JQuery includes the toggleClass() method, which works the same as JavaScript's toggle() method. We can take an HTML element as a reference to the toggleClass() method and pass the class name as a parameter.
grammar
Users can use JQuery's toggleClass() method to switch element classes according to the following syntax.
$(element).toggleClass("class_name");
In the above syntax, users should replace the element with the element id, class or tag to access the element using JQuery. class_name is the class name of the reference element to be switched.
Example 3
In the following example, we change the color of the element's text by toggling the element's text_color class using JQuery's toggleClass() method.
In the output, the user can observe that whenever the button is pressed, it switches the text color of the span element between red and the default color.
<html> <head> <style> .text_color { color: red; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> </head> <body> <h2 id="Using-the-i-JQuery-s-toggleClass-method-i-to-toggle-and-element-class-using-JQUery">Using the <i> JQuery's toggleClass() method </i> to toggle and element class using JQUery. </h2> <h3 id="Click-the-below-button-toggle-text-color-class-from-the-below-span-element">Click the below button toggle text_color class from the below span element.</h3> <span>This is a sample text.</span> <br> <br> <button onClick="toggleClass()">Toggle color class</button> <script> function toggleClass() { $("span").toggleClass("text_color"); } </script> </body> </html>
We learned three ways to switch element classes using JavaScript and JQuery. When the user wants to write code in JavaScript, the toggle() method can be used; when the user wants to write code using JQuery, the toggleClass() method can be used.
The above is the detailed content of How to switch element classes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.