The property 'style' in Element[] is not readable

In TypeScript, the document.elementsFromPoint method returns an array of Elements, but the 'Element' type does not have a property called "style". This results in the following error:

Uncaught TypeError: Cannot read property 'style' of undefined.

How can the style of the Element be changed in TypeScript? Here is the code snippet:

document.body.onclick = function(event: MouseEvent) {
            let elements: Array<HTMLElement> = document.elementsFromPoint(event.clientX, event.clientY) as Array<HTMLElement>;
            let divs: Array<HTMLElement> = [] as Array<HTMLElement>;
            for (let i = 0; i < elements.length; i++) {
                if(elements[i].tagName == 'DIV') {
                    divs.push(elements[i])
                }
            }
            if (divs.length == 2) {  // before if OK
                console.log('2 divs!!! Unit is here!');
                let flag: string = document.body.getAttribute('flag');

                if (flag != '1') {
                    document.body.setAttribute('flag', '1');
                    divs[2].style.backgroundColor = "rgba( 255, 1, 0, 0.5)";
                }
                else {
                    document.body.setAttribute('flag', '0');
                    divs[2].style.backgroundColor = "rgba( 255, 1, 0, 0.5)";
                }
            }

        };

Answer №1

Make sure to verify the size of your divs collection is 2, and avoid accessing the third array index (JavaScript arrays start at zero).

Consider using divs[1] instead

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

"Update your Chart.js to version 3.7.1 to eliminate the vertical scale displaying values on the left

https://i.sstatic.net/7CzRg.png Is there a way to disable the scale with additional marks from 0 to 45000 as shown in the screenshot? I've attempted various solutions, including updating chartjs to the latest version, but I'm specifically intere ...

Enhance Your NestJS Application by Extending Mongoose Schemas and Overriding Parent Properties

In order to achieve the desired functionality, I have a requirement for my Class B to extend a Class A. This initial step works as intended; however, the next task at hand is overriding a property of Class A within Class B. More specifically, it is necess ...

The TypeScript error message indicates that the property 'forEach' is not found on the 'FileList' type

Users are able to upload multiple files on my platform. After uploading, I need to go through each of these files and execute certain actions. I recently attempted to enhance the functionality of FileList, but TypeScript was not recognizing the forEach m ...

The type 'void' cannot be assigned to the type 'ReactNode'

Having trouble with the total amount calculation due to the nature of the calculateTotal function import CartItem from "./CartItem" import {CartItemType} from '../App' import {Typography,Stack} from '@mui/material'; type Props ...

Having trouble with implementing Spotify OAuth in NextJS?

I am in the process of creating a music website portfolio using Spotify and NextJS. I want to incorporate music playback on the website, but I am encountering issues with Spotify authentication. When I click the login button, I receive a 405 HTTP status er ...

Discovering errors within a reactive form in Angular using a loop to iterate through the FormArray

I am currently utilizing Angular CLI version 16.2.1. As I progress through a course, I am working with reactive forms. In a list of 'Recipes', I aim to include a Recipe with various inputs and a collection of ingredients. However, I am encounter ...

What is the most effective method for designing a scalable menu?

What is the most effective way to create a menu similar to the examples in the attached photos? I attempted to achieve this using the following code: const [firstParentActive, setFirstParentActive] = useState(false) // my approach was to use useState for ...

Create seamless communication between Angular application and React build

I am currently engaged in a project that involves integrating a React widget into an Angular application. The component I'm working on functions as a chatbot. Here is the App.tsx file (written in TypeScript) which serves as the entry point for the Rea ...

Guide on releasing a TypeScript component for use as a global, commonJS, or TypeScript module

I have developed a basic component using TypeScript that relies on d3 as a dependency. My goal is to make this component available on npm and adaptable for use as a global script, a commonJS module, or a TypeScript module. The structure of the component is ...

Component that can be used multiple times to load data

I am currently working on a react/nextjs/redux application where each component needs to call a different backend API. The main challenge I am facing is the lack of reusability in loading data components due to some repetitive code that I would like to el ...

Deploying Firebase functions results in an error

Just recently started exploring Firebase functions. Managed to install it on my computer, but running into an error when trying to execute: === Deploying to 'app'... i deploying firestore, functions Running command: npm --prefix "$RESOURCE_ ...

How can we create a unique type in Typescript for a callback that is void of any return value?

When it comes to safe callbacks, the ideal scenario is for the function to return either undefined or nothing at all. Let's test this with the following scenarios: declare const fn1: (cb: () => void) => void; fn1(() => '123'); // ...

When attempting to display an identical image on two distinct canvas elements in Angular 6

I am facing an issue where the image is only rendered on the second canvas instead of both canvases. I need assistance in finding a solution to render the same image on both canvases. Below is a screenshot demonstrating that the image is currently only re ...

A guide on simulating x-date-pickers from mui using jest

I have successfully integrated a DateTimePicker into my application, but I am facing an issue with mocking it in my Jest tests. Whenever I try to mock the picker, I encounter the following error: Test suite failed to run TypeError: (0 , _material.gen ...

Unleashing the power of Typescript enums in conjunction with external modules through browserify

Previously, I utilized TypeScript internal modules and included numerous script tags to initialize my app. Now, I am in the process of transitioning the project to utilize external modules (using browserify), but I have hit a roadblock when it comes to con ...

Facing numerous "error TS1005" messages when performing a gulp build due to node_modules/@types/ [prop types] and [react] index.d.ts with SPFx Webpart

I am currently in the process of developing a custom spfx webpart that includes a feature to display link previews. In order to achieve this functionality, I integrated this specific library. However, I encountered some challenges during the implementation ...

Sending Component Properties to Objects in Vue using TypeScript

Trying to assign props value as an index in a Vue component object, here is my code snippet: export default defineComponent({ props:{ pollId:{type: String} }, data(){ return{ poll: polls[this.pollId] } } }) Encountering errors wh ...

Creating a sequence of HTTP calls that call upon themselves using RxJs operators

When retrieving data by passing pageIndex (1) and pageSize (500) for each HTTP call, I use the following method: this.demoService.geList(1, 500).subscribe(data => { this.data = data.items; }); If the response contains a property called isMore with ...

The module called "discord.js" does not have a component named "Intents" available for export

Issue with importing module '"discord.js"' - 'Intents' not exported. Here is the code in question: import dotenv from 'dotenv'; const bot = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents. ...

Assign a class to a button created dynamically using Angular

While working on my project, I encountered an issue where the CSS style was not being applied to a button that I created and assigned a class to in the component.ts file. Specifically, the font color of the button was not changing as expected. Here is the ...