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

https://codepen.io/krishnansgitrepo/pen/NWBqJQj

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

Thanks,
Vijay

Y
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.

Example:

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

Now you have the following CSS:

p.one
{
    color: #f00;
}
p.two
{
    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");

<body>
  <img class="one" src='http://assets.stickpng.com/thumbs/580b585b2edbce24c47b2704.png' alt='photos' height='150px'/>
  <img class="two" src='https://static.vecteezy.com/system/resources/previews/001/193/929/non_2x/vintage-car-png.png' alt='photos' height='150px'/>
  <img class="one" src='https://www.kindpng.com/picc/m/381-3816942_indoor-plants-png-transparent-png.png' alt='photos' height='150px'/>
  <img class="one" src='https://www.freepnglogos.com/uploads/dog-png/bow-wow-gourmet-dog-treats-are-healthy-natural-low-4.png' alt='photos' height='150px'/>
  <img src='https://assets.webiconspng.com/uploads/2017/09/House-PNG-Image-45779.png' alt='photos' height='150px'/>
</body>


img.one {
  border:4px solid black;
}

img.two {
  border: 4px solid red;
}

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

console.log(imgLst.length);
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;');
//  }
 //console.log(i++);
//});