Home > Blockchain >  Change css class attribute values using javascript
Change css class attribute values using javascript

Time:01-03

I want to change the value of one of the attributes of css class dynamically

Here's my scenario:

I've many elements using one class, instead of getting them all and looping them over and applying style, I want to change the value of one of the attributes of class, which is alredy applied on them. for example

.prodName {
  max-width: 270px;
  display: block;
}

above class is being used by many elements, and I want to alter one of the attributes of that class like

.prodName {
  max-width: 350px <---
  display: block;
}

is there any simple method for this in javascript.

Before I post this question, I already searched but didn't find anything easy and useful. thanks in advance to helping hands.

CodePudding user response:

You can use CSS variables for this case.

const root = document.querySelector(':root');

function play() {
  root.style.setProperty('--size', '300px');
}
:root {
  --size: 100px;
}

.container {
  background-color: red;
  width: var(--size);
  height: var(--size);
  cursor: pointer;
}
<div  onclick="play()"></div>

The only problem with the above approach is support in older browsers. If you have to support IE, and older browsers where CSS variable support is not present, you can handle this problem by adding a class to the body/parent container.

function play() {
  document.body.classList.add('large')
}
.container {
  background-color: red;
  width: 100px;
  height: 100px;
  cursor: pointer;
}

.large .container {
  width: 300px;
  height: 300px;
}
<div  onclick="play()"></div>

CodePudding user response:

Add new class to CSS:

.mw350 {
  max-width: 350px;
}

Then add new class to the element in JS:

document.querySelector('.prodName').className  = ' mw350'; // <-- better to select using unique IDs, like '#prodNameElement'

CodePudding user response:

If you are going to control the css class/attribute change from ts, maybe with a function or var change, you might want to use ngClass: https://www.freecodecamp.org/news/angular-ngclass-example/ and have all the logic where you want it, easily accessible.

  • Related