Replace all instances of a CSS class using vanilla JS

Simple DOM manipulation in only 3 lines of code

By: Ajdin Imsirovic 07 March 2020

Recently I was looking at some commits on Github, and the lines of code were very long. They didn’t wrap but rather just disappeared on the right edge of a centered container. Here’s what I did to make it a bit more user-friendly for myself.

Replace all instances of a CSS class using vanilla JavaScript Image by CodingExercises

So I figured there must be a class that sets the container’s width and centers it. Indeed, there was: the CSS class name was container-lg.

I guess this class is implemented on desktops (from which I was inspecting the commit’s code).

However, due to the fact that the code was overflowing its container, it was kind of annoying to use the scrollbar to read the code on the right-hand side of each overflowing line of code.

So I figured there must be a container-fluid class that I could replace container-lg with, and make the container fluid, i.e make the container span the full width of the viewport.

This was definitely the case. But how to quickly replace one CSS class with another in vanilla JS, using browser’s own JavaScript console?

A simple way to replace one CSS class with a different CSS class in vanilla JS

To do this, you need only 3 lines of code:

let a = document.getElementsByClassName( "container-lg" );
[...a].forEach( x => x.className += " container-fluid" );
[...a].forEach( x => x.classList.remove("container-lg") );

Here’s how the code above works:

  1. First we get all elements with the class name of container-lg - the stored variable a is an array-like collection.
  2. Being an array-like collection, we can’t run the forEach method on a, so we need to convert it to an array. A quick and easy way to do this is: [...a] - we’re using the spread operator, ...
  3. Finally, we can run the forEach method now, and we do it twice. The first time we run it, we append another class name to the list of class names on all the members of the a array. The newly-appended class name is container-fluid. The second time we run the forEach, we remove the container-lg class from the classList on all the members of our a array. Simple!

This is a fast and easy way to remove all occurences of a CSS class on all elements on a web page, and replace them with a different CSS class.

Feel free to check out my work here: