Replace class with javascript

How to add, remove, and toggle CSS classes in JavaScript

As a web developer, you are often required to add, remove, and toggle CSS classes based on user interactions with elements on the web page. If you had already used jQuery in the past, you’d be probably familiar with the addClass() , removeClass() , and toggleClass() methods.

In modern JavaScript, it makes no sense to load the complete jQuery library to do some simple DOM manipulations. In this article, you’ll learn how to add, remove, and toggle CSS classes in JavaScript without jQuery.

The simplest way to get and set CSS classes in JavaScript is using the className property. It refers to the value of the HTML element’s class attribute. Let us say we have the following HTML element:

The following example shows how to add a new CSS class or replace all existing CSS classes of the above

element:
const pizza = document.querySelector('.pizza') // print existing classes console.log(pizza.className) // pizza // add new `.spicy` class pizza.className += 'spicy' // replace all existing classes pizza.className = 'hot spicy pizza' 

Since class is a reserved word in JavaScript, the name className is used for this property. This property is supported by all modern and old browsers, including Internet Explorer.

Читайте также:  Writing log files python

There is even a better way to manipulate CSS classes in JavaScript, thanks to the classList property. It is a read-only property that returns a live DOMTokenList collection of all the classes applied to the element. The classList property works in all modern browsers and IE10 and above. You can use the classList property to easily add, remove, and toggle CSS classes from an element in vanilla JavaScript. Say we have an element like the below:

div class="hot spicy pizza"> 🍕 div> 
// grab element reference const pizza = document.querySelector('.pizza') // get all existing classes console.log(pizza.classList) // ["hot", "spicy", "pizza", value: "hot spicy pizza"] // get first class name console.log(pizza.classList[0]) // hot // get total number of classes console.log(pizza.classList.length) // 3 

Let us now look at the popular methods of the DOMTokenList collection, returned by the classList property. We’ll use these methods to manage and update CSS classes for an HTML element.

The item() method returns the class in the collection by its index, or undefined if the index is greater than or equal to the list’s length property:

console.log(pizza.classList.item(1)) // spicy 
pizza.classList.add('sauce', 'cheese', 'tomato') 
div class="hot spicy pizza sauce cheese tomato"> 🍕 div> 

If you try to add a class that already exists, the add() method will ignore it. To see how it works, let us add more cheese to the pizza:

div class="hot spicy pizza cheese tomato"> 🍕 div> 
console.log(pizza.classList.contains('cheese')) // true console.log(pizza.classList.contains('yogurt')) // false 
pizza.classList.remove('sauce', 'potato') 

If you try to remove a class that doesn’t exist, as we did in the above example, there won’t be any error. JavaScript will completely ignore it.

The toggle() method removes the class if it already exists. Otherwise, it adds to the collection. Without this method, you have to manually check if the class exists using contain() before toggling it on or off:

// manual toggle if (pizza.classList.contains('olive'))  pizza.classList.remove('olive') > else  pizza.classList.add('olive') > 
pizza.classList.toggle('olive') 
const status = pizza.classList.toggle('olive') console.log(status) // true --> class was added 

You can also pass a second boolean parameter to the toggle() method to indicate whether to add the class or remove it. This will turn toggle() into one way-only operation. If the second argument evaluates to false , then the class will only be removed but not added. If it evaluates to true , then the class will only be added but not removed. Here is an example:

const status = pizza.classList.toggle('hot', false) console.log(status) // false --> class was removed 
pizza.classList.replace('spicy', 'olive') 

This method returns true if the target class is successfully replaced with the new class. Otherwise, false .

The replace() method is not supported by Internet Explorer. You can use remove() along with add() to replace a CSS class in older browsers.

// iterate over all classes pizza.classList.forEach((item, index) =>  console.log(item) >) 

That’s all! In this article, we looked at two properties ( className & classList ) to manipulate CSS classes in JavaScript. The className property presents the class attribute of the element and is supported by all browsers, including Internet Explorer. It can be used to add a new class or replace an existing class. On the other hand, the classList property returns a live DOMTokenList collection of all the classes applied to a DOM element. It can easily add, remove, toggle, and iterate through all CSS classes. Read Next: Hide and show DOM elements using a CSS class in JavaScript ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Add Remove, Toggle or Replace Class of an Element in JavaScript

Almost all website projects that we work on require us to change the classes of different HTML elements at one time or other. We can do this very easily using jQuery. However, using a library just to change or manipulate the classes of different DOM element is overkill. In this post, we will cover different methods to achieve all this using pure JavaScript.

Add a Class to an HTML Element Using className

The className property can be used to get or set the value of the class attribute of any DOM element. The returned string contains all the classes of current element separated by a space. We can simply use the += operator to append any new classes to our element.

document.getElementById("theId").className += " extraClass"; document.querySelector("selector").className += " extraClass";

If you want to add a class to multiple HTML elements at once, you can use the document.querySelectorAll() method to do so.

var elems = document.querySelectorAll("selector"); var elemCount = elems.length; for (var i = 0; i

You can also use the document.querySelectorAll() method to assign extra classes a selected HTML element at a specific index.

document.querySelectorAll("selector")[index] += " extraClass";

One disadvantage of adding classes this way is that if you are not careful, a class might be added several times. We can implement a check to see if class already exists for an HTML element and not add it if it does.

var elem = document.getElementById("theId"); if(elem.className.match( /(^|\s+)extraClass($|\s+)/g))

Remove a Class From an HTML Element Using className

You can also use the className property to remove a specific class from the class attribute of an HTML element. This requires the use of regex to replace the unwanted class with an empty string.

var elem = document.getElementById("theId"); elem.className = elem.className.replace( /(^|\s+)extraClass($|\s+)/g , '' );

In the above regular expression, the first capture group either captures the beginning of a string or any whitespace characters. Similarly, the second capture group either captures the end of a string or any whitespace characters. The string between these two capture groups is the class name that you want to replace. Here are some of the results of using the above regular expression to replace unwanted classes:

Regular Expression — (^|\s+)dark($|\s+)/g Classes — "heading page-title dark large" After Removal — "heading page-title large" Regular Expression — (^|\s+)title($|\s+)/g Classes — "heading page-title dark large" After Removal — "heading page-title dark large" Regular Expression — (^|\s+)large($|\s+)/g Classes — "heading page-title dark large" After Removal — "heading page-title dark"

In the second case, there was no title class in the whole list so nothing was replaced. The page-title class remained intact.

Just like the previous section, you can loop through multiple elements and remove a class from all of them using the docment.querySelectorAll() method.

Replace all Classes of an HTML Element with New Ones Using className

You can also replace all classes of an HTML element with new ones by assigning the new class string to that element instead of appending it to the original set of classes.

document.getElementById("theId").className = "firstClass secondClass"; document.querySelector("selector").className = "firstClass";

Similarly, you can assign new classes to multiple elements by looping over them.

var elems = document.querySelectorAll("selector"); var elemCount = elems.length; for (var i = 0; i

Adding, Removing and Replacing Classes Using classList

If you are working with modern browsers, you can avoid the use of regular expressions while changing the classes of an HTML element. All modern browsers as well as Internet Explorer 10 and above support a classList property for DOM elements. This property has some useful methods which can add and remove classes from the class attribute of any HTML element.

The add(String [, String]) method accepts name of one or more classes as its parameters. These classes are added to the original HTML element on which this method was called. If any of those classes already exist in that element, there will be ignored. This way you can be sure that the same class is not added multiple times.

The remove(String [, String]) method also accepts name of one or more classes as its parameters. All the classes supplied to this method will be deleted from the list of classes initially applied on the calling HTML element. One good thing about the method is that it will not through an error if the class that you’re going to delete does not already exist in that element.

You can also use the toggle(String [, force]) method to toggle a class currently applied on the calling HTML element. If the class already exists, it will be removed and the method will return false . If a class does not exist, it will be added to the list of classes and the method will return true . The force parameter is a Boolean value which can be used to forcefully add or remove a class from the calling HTML element. A class will be added if the value of force evaluates to true . Similarly, the class will be removed if the value of force evaluates to false .

Instead of adding or removing classes, you might sometimes be interested in replacing an old class with a new one. This can be achieved using the replace(oldClass, newClass) method. The first parameter passed to this method is the old class that you want to replace. The second parameter is the new class meant to take the place of old class.

The class list property also has a contains(String) method which can check if an HTML element contains a class or not.

var theClassList = document.querySelector("selector").classList; theClassList.add('firstClass'); theClassList.remove('secondClass'); theClassList.toggle('thirdClass'); theClassList.replace('thirdClass', 'fourthClass');

Quick Summary

Let’s recap everything that we have covered in this tutorial.

  1. If you have to support older browsers the best way to add, remove or replace any class in an HTML element is to use the className property. However, you will have to be careful about a few things like not adding a class multiple times etc.
  2. If you don’t have to support older browsers the best way to change the classes of an HTML element is to use the classList property. This will take care of everything for you.

Let me know if there is anything that you would like me to clarify in this tutorial. Also, you are more than welcome to comment if you know other techniques to add, remove or replace the classes of an HTML element using JavaScript.

Rate this post —

Источник

Оцените статью