user963063 user963063 - 3 months ago 13
Javascript Question

How to manipulate style for a div during js process?

Just go for a few loops and then display different value for a given DIV but the style for this DIV failed to be set dynamically, any idea? How to fix it? Fyi, the style section, i have set it for this DIV as well. But once the value changes the style is gone (style set via the Style section is no longer valid).
Thanks.

var i = 60; // set your counter to 60

function myLoop () { // create a loop function
setTimeout(function () { // call a 3s setTimeout when the loop is called
if (i < 100) {
i += 10; // increment the counter by 10
console.log(i);
// document.getElementById('score').style = "margin: 0; position: absolute; top: 50%; margin-right: -50%; font-size: 216px; transform: translate(-50%, -50%);color: red;";
document.getElementById('score').innerHTML = i;
myLoop(); // .. again which will trigger another
}
}, 3000)

}

Answer

element.style refers to the style property object (https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) , not the attribute. try

document.getElementById('score').setAttribute("style", 
"margin: 0; position: absolute; top: 50%; margin-right: -50%; font-size: 216px; transform: translate(-50%, -50%);color: red;");