Replace all instances of a CSS class using vanilla JS
Simple DOM manipulation in only 3 lines of code
is a developer, technical writer, and a (former) designer.
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.
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
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.
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:
- First we get all elements with the class name of
container-lg- the stored variable
ais an array-like collection.
- Being an array-like collection, we can’t run the
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,
- Finally, we can run the
forEachmethod 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
aarray. The newly-appended class name is
container-fluid. The second time we run the
forEach, we remove the
container-lgclass from the
classListon all the members of our
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.