Skip to content Skip to sidebar Skip to footer

Property 'style' Does Not Exist On Type 'element'

here the code function showTab(n) { // This function will display the specified tab of the form... var x = document.getElementsByClassName('tab'); x[n].style.display = 'blo

Solution 1:

It's a bit of a pain. :-) The problem is that documents can contain both HTML elements (HTMLElement) and other kinds of elements, so the various DOM methods can only assume the type Element for what they return, not HTMLElement. Element doesn't have a style property.

Separately, once you resolve the issue with x[n], you'll have an issue with the fact that getElementById can return null.

If you're only dealing with HTML elements, you might give yourself some convenience wrappers that (at least in dev mode) test the assertion that the results are HTML elements, so you can then assume they are in later code:

Here's a rough and ready example:

// An assertion type guard that throws if given a non-HTMLElementfunctionassertHTMLElement(el: Element): asserts el is HTMLElement {
    if (!(el instanceofHTMLElement)) {
        thrownewError(`Element is not an HTML element`);
    }
}

// A "get element by ID" that requires an HTMLElement and that the// element does exist (never returns `null`)functiongid(id: string): HTMLElement {
    const el = document.getElementById(id);
    if (el === null) {
        thrownewError(`No element with id "${id}" found`);
    }
    assertHTMLElement(el);
    return el;
}

// A "query selector all" that ensures all matching elements are HTMLElementsfunctionqsa(selector: string): HTMLElement[] {
    const list = document.querySelectorAll(selector);
    returnArray.prototype.map.call(list, el => {
        assertHTMLElement(el);
        return el;
    }) asHTMLElement[];
}

Then your code would use them:

functionshowTab(n: number) {
    // This function will display the specified tab of the form...const x = qsa(".tab");
    x[n].style.display = "block";
    //... and fix the Previous/Next buttons:if (n == 0) {
        gid("prevBtn").style.display = "none";
    } else {
        gid("prevBtn").style.display = "inline";
    }
    if (n == (x.length - 1)) {
        gid("nextBtn").innerHTML = "Submit";
    } else {
        gid("nextBtn").innerHTML = "Next";
    }
    // ...
}

Playground link

Note I've also added a type to n, since it was defaulting to any.


Side note: I'd suggest using classes rather than inline styling.

Post a Comment for "Property 'style' Does Not Exist On Type 'element'"