網站搜尋

javascript - TypeScript 為 HTMLCollectionOf、NodeCollection 設置 CSS 樣式,Google 自動完成功能表單


我如何為 HTMLCollectionOf 或 NodeCollection 設置 CSS 樣式?

 let items = document.querySelectorAll('.pac-item') as NodeListOf<HTMLElement>;

對於 HTMLElement 設置樣式工作良好

答案#1

謝謝大家!我的錯...那是一個元素的集合...通過迭代解決了它

 var items:any = document.getElementsByClassName('pac-item');
        for (let i = 0; i < items.length; i++) {
            let element = items[i];
            element.style.background = '#2B2B2B';
            element.style.color = '#DEDEDE';
        }

答案#2

TypeScript 定義表明 HTMLCollectionOf 是 HTMLCollection 的擴展,您需要對其進行迭代以訪問個別元素。

interface HTMLCollectionOf<T extends Element> extends HTMLCollection {
    item(index: number): T;
    namedItem(name: string): T;
    [index: number]: T;
}

我希望這對你有幫助。:)