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