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

How to switch element classes in JavaScript?

WBOY
Release: 2023-08-24 17:29:13
forward
1067 people have browsed it

如何在 JavaScript 中切换元素类?

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"); 
Copy after login

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>Using the <i> toggle() method </i> to toggle and element class using JavaScript.</h2>
   <h3>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>
Copy after login

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");
} 
Copy after login

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>Using the <i> contains(), add(), and remove() method </i> to toggle and element class using JavaScript. </h2>
   <h3>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>
Copy after login

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"); 
Copy after login

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>Using the <i> JQuery's toggleClass() method </i> to toggle and element class using JQUery. </h2>
   <h3>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>
Copy after login

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!

source:tutorialspoint.com
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!