W
W
Wadnory2022-01-22 20:32:10
css
Wadnory, 2022-01-22 20:32:10

How to pass variables to styles in JavaScript?

let lights = Array.from(document.querySelectorAll('.light'))
    let speedValue = 250
    for (let node of lights) {
      node.style.animationDuration = `${speedValue}ms`
    }


<div className='lights'>
      <div className='light'></div>
      <div className='light'></div>
      <div className='light'></div>
      <div className='light'></div>
      <div className='light'></div>
      <div className='light'></div>
      <div className='light'></div>
    </div>


If node.style.animationDurationI manually write a value, for example "250ms",
then everything will change perfectly and there will be no errors. But if you change the value using a
variable (as in my code above), it gives an error: Question: How can I fix it so that I can change the value using a variable?

Uncaught TypeError: lights is not iterable

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
I Phoenix I, 2022-01-23
@Wadnory

querySelectorAll still returns an array, it does not need to be additionally wrapped with another array.
Without Array.from everything enumerates fine

A
Anton Shamanov, 2022-01-23
@SilenceOfWinter

node.style - a string, you need to parse it into an array and then assemble it back into a string or do a pattern replacement /([-\w]+)\s*:\s*([^;]+);?/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question