Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
How to adjust custom css properties dynamically?

I am creating a js for an HTML file. I want to manipulate the css of the div.

One of the ways is to use this: -

div.style.left = "30px";

However, in my code user tells how the HTML is to be manipulated. I want to make it dynamic. I have set a variable with the property I want to change like this: -

let myProperty = "top", value = "30px";

Now, I want to use this as my CSS modifier in js like this: -

myDiv.style.myProperty = value;

I have tried setAttributes() which is not working. How can I do this?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You have to use square brackets to access an object property using a variable.

For example:

let myProperty = "top", value = "30px";
myDiv.style[myProperty] = value;
about 4 years ago · Juan Pablo Isaza Relatório

0

In your style.css create two different styles with different class names.

In your HTML use the default styling.

In your JS:


const someHTMLTag = document.getElementById("demo")

if(condition) {

   someHTMLTag.className = firstStyle

} else {

   someHTMLTag.className = secondStyle

}
about 4 years ago · Juan Pablo Isaza Relatório

0

I don't have enough reputation to add a comment to get more information, but here's my attempt at providing you with an answer to what you have written in your original question.

You could provide the div with a class or id in the HTML (<div id="idName">...</div>) and have the js file access it via the DOM.

var myDiv = document.getElementById("idName");
myDiv.setAttribute("class", "className");

Or

var myDiv = document.getElementById("idName");
myDiv.style.value = "30px";
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda