TS2339: Property 'style' does not exist on type 'Element'

后端 未结 3 715
悲&欢浪女
悲&欢浪女 2020-12-19 15:38

Here\'s the code:

const test = Array.from(document.getElementsByClassName(\'mat-form-field-infix\'));
test.forEach((element) => {
    element.outerHTML =          


        
相关标签:
3条回答
  • 2020-12-19 15:58

    When you set the outerHTML, you're destroying the original element that was there. So, your styling doesn't work.

    You'll notice that if you change it to set innerHTML, your styling does work.

    This does not do the same exact thing, but I hope it points you in the right direction.

    const test = Array.from(document.getElementsByClassName('mat-form-field-infix'));
    test.forEach((element) => {
        element.innerHTML = '<div class="good-day-today" style="width: 0px;"></div>'; // Please note that this line works fine!
        element.style.padding = '10px';
        element.style.borderTop = '0';
    });
    
    0 讨论(0)
  • 2020-12-19 16:02

    You need a typecast:

    Array.from(document.getElementsByClassName('mat-form-field-infix') as HTMLCollectionOf<HTMLElement>)
    

    That's because getElementsByClassName only returns HTMLCollection<Element>, and Element does not have a styleproperty. The HTMLElement however does implement it via it's ElementCSSInlineStyle extended interface.

    Note that this typecast is typesafe in the way that every Elementis either a HTMLElement or an SVGElement, and I hope that your SVG Elements don't have a class.

    0 讨论(0)
  • 2020-12-19 16:04

    Another option is to use querySelectorAll and a type parameter. getElementsByClassName is not generic, but querySelectorAll is - you can just pass the type of the elements that will be selected, like this:

    const test = document.querySelectorAll<HTMLElement>('.mat-form-field-infix');
    

    This doesn't require any type casting, and it will allow you to use forEach immediately, rather than converting it to an array first. (getElementsByClassName returns an HTMLCollection, which does not have a forEach method; querySelectorAll returns a NodeList, which does have a forEach method, at least on somewhat up-to-date browsers. To support ancient browsers too, you'll need a polyfill, or convert it to an array first.)

    If you happen to just need a single element, you can use querySelector, which is generic as well:

    const elm = document.querySelector<HTMLElement>('.foo')!;
    elm.style.padding = '10px';
    
    0 讨论(0)
提交回复
热议问题