Search code examples
typescriptstrong-typing

Cannot read property 'style' in Element[]


TypeScript. document.elementsFromPoint return Element[], but the 'Element' does not contain such a property as "style". As a result, i'm getting:

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

How to change the style of the 'Element' in the TypeScript. My code:

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)";
                }
            }

        };

Solution

  • You're checking that the length of your divs array is 2, and then you attempt to read from the 3rd array element (arrays in JavaScript are zero-indexed).

    Try changing it to divs[1]