VSCode 的智能感知是按照 TypeScript/lib.es6.d.ts 的定义来的,在这个定义里面,getElementById 返回的是 HTMLElement,而 getElementsByClassName 返回的是 HTMLCollectionOf(即集合内的元素是 Element)。
HTMLElement 继承自 Element,HTMLElement 有 style 属性但是 Element 没有,所以对 getElementsByClassName() 返回的值访问 style 是没有提示的。
其实 getElementById 的定义是错的,按照规范,getElementById 返回的应该是一个 Element 而不是 HTMLElement,但是因为 getElementById 太常用,而且实际使用中绝大多数都是返回的 HTMLElement,如果 d.ts 里面正确定义成 Element 反而会造成很多困扰,所以干脆把它的返回类型定义成 HTMLElement。...
there was complainant before saying that it was too cumbersome to always cast the type Element to HTMLElement when in most common cases the actual type is HTMLElement, even though the spec says it should be Element.
For example, the return type of getElementById is defined as Element, however we made it HTMLElement to avoid too much casting.
...
如果你用 TypeScript,做一下类型 cast 就行了:
const nodes = document.getElementsByClassName('className') as HTMLCollectionOf
如果用 JS,试试用 JSDoc 做 cast:
/*** @type {HTMLCollectionOf}*/
const nodes = document.getElementsByClassName('className')