Killon
Killon

Reputation: 31

How to change a variable inside a style attribute

I have a div tag with a style attribute, I'm trying to change the value of the style attribute with javascript

i've tried with

document.getElementById("box").style

but still can't modify the --s variable

This is how it was originally:

Html

<div id="box" style="--s:1">

Then i took the style attribute in the js:

Html

<div id="box">

Javascript

document.getElementById("box").style="--s:1"

But still I don't know how can I modify --s with another value of another variable. thank you for your time and for any answers

EDIT: the code is based on the first answer of this topic: CSS 360 rotating progress radial using JS

Upvotes: 3

Views: 4569

Answers (3)

Mister Jojo
Mister Jojo

Reputation: 22392

the answer is in this post => CSS 360 rotating progress radial using JS

  deg = deg + 10;
  ele.style.setProperty("--v", deg+'deg');

you didn't read it correctly !

in your case this is:

document.getElementById("box").style.setProperty("--s", 1);

everything about this question is about CSS custom properties https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties

I have done another sample code usage here: Html & JS rotate image 90 degrees on click

Upvotes: 4

Scott Marcus
Scott Marcus

Reputation: 65853

When you access the style property of a DOM object, you are accessing a CSSStyleDeclaration object. You don't set style equal to something. You access properties of that style object (left, color, top, etc.). If you assign a value to style, you wipe out the object stored in that property and instead just make the property hold the string you set it to, which breaks styling functionality.

If you want to change the value of the HTML style attribute (rather than accessing the style DOM property), use the setAttribute method:

document.getElementById("box").setAttribute("style", "--s:1");

Upvotes: 0

EddiGordo
EddiGordo

Reputation: 686

try with attributes :

document.getElementById("box").getAttribute("style") // for reading value
document.getElementById("box").setAttribute("style", "background: red;") // for writing

Upvotes: -2

Related Questions