Typescript Error: Property 'append' does not exist on type 'HTMLElement'
Asked Answered
G

3

8

The Problem:

I'm receiving a Typescript 2.2.1 compilation error when trying to append a compiled angular 1.5 template to an existing HTMLElement.

Code:

$document.find(scope.target)[0].append($compile(menu)(scope)[0]);

Compile error:

[ts] Property 'append' does not exist on type 'HTMLElement'

I've searched through the type definitions and don't see a signature for append().

Any ideas as to which type or version of typescript I should be using?

Thanks!

Griffen answered 21/6, 2017 at 22:22 Comment(2)
Have you tried appendChild? append is experimental and not on all browsers.Lal
@AndrewLi No, not yet. I'm converting existing working .js code into typescript. So, I was hoping I wouldn't have to change any internals and could just create the typescript "container".Griffen
K
9

Here there is nothing to do with TypeScript.

The correct method to call is appendChild:

https://developer.mozilla.org/en/docs/Web/API/Node/appendChild

append is a jQuery method, and if you want to use that you could do:

$document.find(scope.target).append($compile(menu)(scope)[0]);

and it should work too.

I hope it helps

Kendricks answered 21/6, 2017 at 22:36 Comment(0)
K
1

There is an append/prepend function on HTMLElement. The problem that it is currently still experimental.

In order to use it without getting errors from TypeScript I used it as any ¯\_(ツ)_/¯ (<any>myElement).append(otherElement)

Kingship answered 12/4, 2018 at 6:2 Comment(1)
This is a good solution. Better syntax would be: (myElement as any).append(otherElement)Rebekah
C
0

Element.append() now exists (since 2016). If TypeScript is finding an error:

  • Types: ensure that it's an Element and not just a Node
  • Config: ensure you're loading the DOM library
  • Config: ensure you're using a recent ES target/lib

Example config:

{
  "compilerOptions": {
    "target": "es2020",
    "lib": ["dom", "es2019", "es2020", "dom.iterable"]
  }
}
Capillary answered 24/6, 2021 at 4:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.