"JavaScript encountered an Uncaught TypeError: Cannot read property 'style' of undefined

Looking to create a local time clock using HTML, here is the code:

<body>
    <div class="container text-center">
        <div class="row">
            <div class="col-xs-12 col-sm-6">
                <div id="seattle" class="clock rounded-circle">
                    <div class="hand second"></div>
                    <div class="hand hour"></div>
                    <div class="hand minute"></div>       
                </div>
            </div>
        </div>
    </div>
    <script src="main.js"></script>
</body>
</html>

Javascript used:

var second = document.getElementsByClassName("second");
var minute = document.getElementsByClassName("minute");
var hour = document.getElementsByClassName("hour");
var curDate = new Date();

function updateDate() {
    s = curDate.getSeconds();
    m = curDate.getMinutes();
    h = curDate.getHours();

    var hourDeg = (h / 12) * 360 + ((m / 60) / 12) * 360 + (((s / 60) / 60) / 12) * 360;
    var minuteDeg = (m / 60) * 360 + ((s / 60) / 60) * 360;
    var secondDeg = (s / 60) * 360;

    second.style.transform = `rotate(${ secondDeg }deg)`;
    minute.style.transform = `rotate(${ minuteDeg }deg)`;
    hour.style.transform = `rotate(${ hourDeg }deg)`; 
}
//setInterval(updateDate, 1000);
updateDate();

Designed with CSS:

.minute {
    width: 3px;
    background-color: #333;
    height: 90px;
    transform: translateX(100px);
}

.hour {
    width: 5px;
    background-color: rgb(44, 11, 235);
    height: 60px;
    transform: translateX(100px);
}

.second {
    width: 1px;
    background-color: rgb(191, 22, 22);
    height: 90px;
    transform: translateX(100px);
}

Question arises - Why does it show "Uncaught TypeError: second.style is undefined"? The "second" element has been declared in the html and its style defined in the css. Any help would be appreciated.

Answer №1

getElementsByClassName() retrieves an array of HTML elements, requiring iteration over each one.

A possible solution using your current code

// update
second[0].style.transform = `rotate(${ secondDeg }deg)`;
minute[0].style.transform = `rotate(${ minuteDeg }deg)`;
 hour[0].style.transform = `rotate(${ hourDeg }deg)`; 

second[0] references the first child element with the class name second.

Utilizing IDs

<!--html-->
<div id="second" class="hand second"></div>
<div id="hour" class="hand hour"></div>
<div id="minute" class="hand minute"></div>  
// javascript

// accessing elements like this
let second = document.getElementById("second");
let hour = document.getElementById("hour");
let minute = document.getElementById("minute");
// ...

Answer №2

Remember to utilize

document.getElementsByClassName('**')[0]

since it will provide you with an array of elements.

Answer №3

getElementsByClassName retrieves an array-like collection of elements (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName). To apply changes to each element, looping through them is necessary. Here's an example:

Array.from(second).forEach(el => {
  el.style.transform = `rotate(${ secondDeg }deg)`;
});

Remember to perform the same process for minute and hour.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Merge JavaScript files from various folders using grunt's configuration settings

I am currently working with Grunt and Sass, and I am in search of a SASS-like feature that will allow me to import any JavaScript file I desire and merge them into a single file based on some configuration depending on the directory I am in. For instance, ...

Monitor the number of ng-repeat items altering within a directive

I am using the angular-sly-carousel directive to display some data. The data is dynamically added as the user scrolls down, so I need to reload the sly carousel options after scrolling. Is there a way to detect when the length of ng-repeat elements change ...

What is the issue with retrieving HTML from an iframe in Internet Explorer when the contents are

Here is the script I used to generate an iframe: Ifrm = document.createElement("IFRAME"); document.body.appendChild(Ifrm); IfrmBod = $(Ifrm).contents().find('body'); IfrmBod.append('<p>Test</p>'); The jQuery function for a ...

Combine the information from 3 separate subscriptions into a single object using RxJS in Angular 9

I am seeking assistance with merging data from 3 different sensors into one object. I am using Cordova plugins to retrieve accelerometer, gyroscope, and magnetometer data. However, I am facing an issue in subscribing to all three observables simultaneously ...

Having trouble with the page redirection issue? Here's how you can troubleshoot and resolve

My goal is to restrict access to both the user home and admin dashboard, allowing access only when logged in. Otherwise, I want to redirect users to the login or admin login page. import { NextResponse } from 'next/server' import { NextRequest } ...

Using Javascript and Node.js to send a JSON request

While browsing through this particular question, I came across a method in node.js to distinguish between html requests and json requests: app.get('/route', function (req, res) { if (req.is('json')) res.json(data); else if (req ...

Execute a bash script from a local URL using fetch

I'm curious about converting a curl command into a bash script with input variables using fetch. It works perfectly in the console: curl -s http://localhost:3001/ident.sh | bash /dev/stdin x627306090abab3a6e1400e9345bc60c78a8bef57 2 10194897676576 ...

As I iterate through a MySQL array, JavaScript is able to manipulate the initial displayed data

I'm struggling to achieve the desired outcome with my code. It seems that when I iterate through an array of data, JavaScript only works on the first echoed data. Here is a snippet of the code: <?php $ids = array(); ...

Updating the value of a key within a jQuery object

A custom modal plugin has been developed with options that can be set by default or by the user. These values are passed to a function for updating, and it is desired that the options object as a whole is updated rather than individual values. The user&ap ...

Is it possible to use JQuery to target input nodes based on their values?

How can I check if any of the file input boxes in my list have a value using just one selector statement? Is it possible to achieve this with code like the following: $('input:file[value!=null]') Or is there another way to accomplish this? ...

Effective technique for connecting client-side JavaScript with server-side node.js

I am striving to create a compact website featuring field auto-completion, drawing suggestions from the server's database (utilizing Node.js + MySQL). What approaches can I take to establish client-server communication as the user inputs data into a ...

Replicate elements along with their events using jQuery

Every time I utilize ajax to dynamically generate new content using methods like .clone(), append(), etc., the newly created element loses all triggers and events that were programmed =( Once a copy is made, basic functionalities that work perfectly on ot ...

"Having trouble getting the onChange function to work with Material-UI's Select

I have encountered an issue while trying to implement the material-ui SelectField component in my project. While the common select component works seamlessly, I face problems when using the SelectField component. The main problem arises with the invocati ...

A guide to generating numerous SVG paths using a JavaScript function

Creating strokes with similar length but different angles of rotations can be achieved efficiently using JavaScript instead of writing redundant lines of code. The following code snippet demonstrates one way to achieve this: function stroke(rot) { var d ...

Strategies for Implementing Multi-Step Password Form Validation

Currently, I am using https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_form_steps as the foundation of my form with some adjustments. Validation is functioning correctly where empty fields disable the next button. However, when I attempt to add ...

Loading tabs dynamically in Angular 2 based on header click event

I successfully created a custom tab component using Angular 2, and it is functioning well with the following usage: <us-tab-verticle> <vtab-content [tabTitle]="'Basic Information'"><basic-info> </basic-info></vtab- ...

Attempting to execute the .replace() method but encountering difficulties

Looking for help with some HTML code: <li><a href="#" class="lstItem">Testing jQuery [First Bracket]</a></li> <li><a href="#" class="lstItem">Loving jQuery [Second one]</a></li> I need to remove the text in ...

Validation of time picker consistently returns false

While using the daterangepicker library for my form validation with JavaScript, I encountered an issue with the time field. It returns false and displays an error message saying: "Please enter a valid time, between 00:00 and 23:59," preventing me from addi ...

An error was encountered while trying to use the 'export' token in lodash-es that was not

Transitioning from lodash to lodash-es in my TypeScript project has been a challenge. After installing lodash-es and @types/lodash-es, I encountered an error when compiling my project using webpack: C:\..\node_modules\lodash-es\lodash. ...

Can someone explain the meaning of the paragraph in the "Index Routes" section of the React-Router documentation?

Lesson 8 of the React-Router tutorial delves into the concept of "Index Routes", outlining the importance of structuring routes in a specific way. Here are some key points from their discussion: The tutorial suggests that while setting up the initial rout ...