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';
Related videos on Youtube
Comments
-
Re_p1ay almost 2 years
how I can set css style for HTMLCollectionOf or NodeCollection
let items = document.querySelectorAll('.pac-item') as NodeListOf<HTMLElement>;
-
gurvinder372 over 6 years
-
Jonas Wilms over 6 yearsYou cant. Iterate over it and assign it to each element :)
-
-
matt forsythe about 5 yearsThis 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>