Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

316
Views
Change css class attribute values using javascript

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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'
about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!