2

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.

3
  • Better add something like .prodName.larger { max-width: 350px; } instead. And apply it to your elements. Commented Jan 2, 2022 at 20:02
  • in JavaScript do element.style.maxWidth = 350px; or, in css do .prodName--larger { max-width: 350px; } Commented Jan 2, 2022 at 20:04
  • I already know these techniques, but there are quite alot of elements with this class name, so is to better approach to add classes based on condition, or change the css class attributes themselves instead. Commented Jan 2, 2022 at 20:08

3 Answers 3

5

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 class="container" 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 class="container" onclick="play()"></div>

Sign up to request clarification or add additional context in comments.

Comments

1

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'

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.