Changing a css class in JS | JavaScript, Node.js, React.js and Angular.js Forum
Yogesh Chawla Posted on 25/12/2022
Hi Yogesh,

this doesn't work when I try to use the css class (blackborder/redborder). it works with inline styling though.


Yogesh Chawla Replied on 25/12/2022

You can't assign a CSS class to a javascript variable.

You can use javascript/jquery to insert your values into HTML elements that are already set up as a class.


        <p class="one">
            I am the first paragraph's text.
        <p class="two">
            I am the second paragraph's text.

Now you have the following CSS:
    color: #f00;
    color: #000;

As it stands the first paragraph will have red text and the second will have black text. However, you can change this in multiple ways using javascript/jquery. One example is below:

document.getElementsByClassName("one").ClassName = "two";
document.getElementsByClassName("two").ClassName = "one";

With the above code, now the paragraph's colors will be switched (it is important to note that you are not limited to only the "=" operator. If you use "+=" you can add, without removing, a class (i.e., an element will be given another class without taking away the old class). To remove a class with javascript, simply use something like, document.getElementsByClassName("one").ClassName = "";

document.getElementsByClassName("one").style.color = "#000";

We can use jquery too as you are using in your code:

$(".one").css("color", "#000");

  <img class="one" src='' alt='photos' height='150px'/>
  <img class="two" src='' alt='photos' height='150px'/>
  <img class="one" src='' alt='photos' height='150px'/>
  <img class="one" src='' alt='photos' height='150px'/>
  <img src='' alt='photos' height='150px'/>
</body> {
  border:4px solid black;

img.two {
  border: 4px solid red;

let imgLst = document.querySelectorAll('img');

let i = 0;

document.getElementByClassName("one").className = "two";

//imgLst.forEach((img) => {
//  if (i % 2 == 0) {
//    img.setAttribute('style', //'border:4px solid black;');
//  } else {
//    img.setAttribute('style', //'border:4px solid red;');
//  }