I am getting some error in my JS code and getting this error Uncaught TypeError: Cannot set properties of undefined (setting ‘transform’)

I have recently starting to learn tailwind and thought to make an analog clock with it here is the html code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>

<body class="bg-slate-900">
    <div class="flex justify-center items-center h-screen">
        <div class="card-container relative">
            <img src="clock.png" alt="Clock">
            <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-9 h-2 w-2.5 rounded-full bg-white"></div>

            <div id="hour" class="hour absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-7 h-24 w-2.5 rounded-full bg-red-600 before:absolute before:h-24 before:w-2.5"></div>

            <div id="minute" class="minute absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-7 h-28 w-2 rounded-full bg-blue-300"></div>

            <div id="second" class="second absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-7 h-36 w-1 rounded-full bg-green-400"></div>
        </div>
    </div>
    <script src=# # "script.js"></script>
</body>
</html>

And here is the js code

// script.js

document.addEventListener("DOMContentLoaded", function() {
    const deg = 6;

    const hor = document.querySelector("#hour");
    const min = document.querySelector("#minute");
    const sec = document.querySelector("#second");

    setInterval(() => {
        const NewDate = new Date();

        let hh = NewDate.getHours() * 30; 
        let mm = NewDate.getMinutes() * deg;
        let ss = NewDate.getSeconds() * deg;

        hor.style.transform = `rotateZ(${(hh) + (mm / 12)}deg)`;
        min.style.transform = `rotateZ(${mm}deg)`;
        sec.style.transform = `rotateZ(${ss}deg)`;
    }, 1000); 
});

It is giving me this error

Uncaught TypeError: Cannot set properties of undefined (setting ‘transform’)

I have tried check all the typos and right DOM method for this but I am still not able to fix this

  • it seems like script.js is trying to access DOM elements before they are fully loaded.

    – 

  • is this a typo? cuz this is invalid <script src=# # "script.js"></script>

    – 

  • I don’t see that error message – jsfiddle.net/6pe57L2b

    – 

Leave a Comment