TypeScript set css style for HTMLCollectionOf<Element>, NodeCollection<Element>,google autocomplete forms

13,596

Solution 1

Thank's guys! My fail...that was collection of elements...resolved it by itteration

 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';
        }

Solution 2

The typescript definition suggests that HTMLCollectionOf is an extension of HTMLCollection and you need to iterate over it to access individual elements.

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

I hope this helps. :)

Solution 3

You're using HtmlCollectionOf, so it is a collection and a collection has many items. Therefore items.style.background does not work because it belongs to HtmlElement.

In other words, you'll have to loop over the collection to apply to each of the HtmlElement. Or you can apply to specific one like below, which I think is what you're trying to do

items[0].style.background = '#2B2B2B';

Share:
13,596

Related videos on Youtube

Re_p1ay
Author by

Re_p1ay

My native country is USSR!

Updated on June 04, 2022

Comments

  • Re_p1ay
    Re_p1ay almost 2 years

    how I can set css style for HTMLCollectionOf or NodeCollection

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

    enter image description here

    For HTMLElement set style working good enter image description here

  • matt forsythe
    matt forsythe about 5 years
    This generates a TypeScript error for me that 'style' does not exist on type 'Element'. The code works if you simply ignore the compiler error, but if you want to make it go away, you need to use document.getElementsByClassName('pac-item') as HTMLCollectionOf<HTMLElement>