Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript compile error: Property 'classList' does not exist on type 'Node'

Windows 7 x64

Compiling using gulp-typescript 2.7.7 using typescript 1.5 beta

Getting error: Property 'classList' does not exist on type 'Node' because of statement document.getElementsByClassName('left-aside-wrapper')[0].classList.toggle('isOpen');

I see that classList is defined in the lib.d.ts file as interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode { classList: DOMTokenList;

Not all that familiar with how d.ts files work so is this my error or is it a bug in the d.ts file that need to be reported?

like image 829
dan Avatar asked Jun 29 '15 00:06

dan


3 Answers

I have got the same issue when I want to update the classList of the fist child.

And my solution is

const element = document.getElementById('testId').firstChild as HTMLElement;

like image 74
Emon Avatar answered Nov 13 '22 16:11

Emon


Use firstElementChild instead of firstChild (i.e. instead of getElementsByClassName('')[0])

So

document.getElementsByClassName('left-aside-wrapper').firstElementChild.classList.toggle('isOpen')
like image 21
Porkopek Avatar answered Nov 13 '22 15:11

Porkopek


This is becuase getElementsByClassName is defined to return Node array and not an Element array.

Not all that familiar with how d.ts files work so is this my error or is it a bug in the d.ts file that need to be reported

Based on https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName I would report it as an error.

like image 8
basarat Avatar answered Nov 13 '22 15:11

basarat