简体   繁体   中英

Why can't I access the style element in Javascript? Firefox console error message says it's “Null”

I use scss and my stylesheet is a minified sheet syle.min.css. I'm trying to make the analog clock project and the style element would get the rotation variable and rotate the hands of the clock respectively.
The code:

    setInterval(setClock, 1000);

const hourHand = document.querySelector('[data-hour-hand]');
const minuteHand = document.querySelector('[data-minute-hand]');
const secondHand = document.querySelector('[data-second-hand]');
//get the current date
function setClock() {
    const currentDate = new Date();
    //gets the current seconds
    const secondsRatio = currentDate.getSeconds() / 60;
    //gets the current minutes plus the socnds so it can gradually glide around the clock
    const minutesRatio = (secondsRatio + currentDate.getMinutes()) / 60;
    //gets the current hours plus the socnds so it can gradually glide around the clock
    const hoursRatio = (minutesRatio + currentDate.getHours()) / 12;
    setRotation(secondHand, secondsRatio);
    setRotation(minuteHand, minutesRatio);
    

setRotation(hourHand, hoursRatio);
}

//rotates the hands clockwise
function setRotation(element, rotationRatio) {
    //this is gonna take what property we want to set this in css so the ratation variable times the 360  
    element.style.setProperty('--rotation',rotationRatio * 360);
}

The problem was the structure. As Martin said, I moved my script tag down and it stops it from returning that error message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM