Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'width' does not exist on type 'HTMLElement'

The following TypeScript fails to compile:

let svg = document.createElement("svg");
svg.width = 300;

Due to the error Property 'width' does not exist on type 'HTMLElement'. But if I change svg to canvas, for example, then it does compile, so it's something about SVGs specifically it seems...

Any ideas?

like image 301
clb Avatar asked Jan 02 '26 02:01

clb


2 Answers

let svg = document.createElement("svg"); doesn't create svg element, but custom html element.

Proper way to create svg element:

let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");

const customSvg = document.createElement("svg")
const properSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg")

console.log(customSvg instanceof SVGSVGElement) // false
console.log(properSvg instanceof SVGSVGElement) // true

console.log(customSvg.width) // undefined
console.log(properSvg.width) // SVGAnimatedLength {}
like image 133
marzelin Avatar answered Jan 03 '26 16:01

marzelin


As Marzelin explained, the proper way to create an svg element is by using document.createElementNS instead:

document.createElementNS("http://www.w3.org/2000/svg", "svg");
  • Related question: Create SVG tag with JavaScript

The TypeScript standard lib knows this well, hence why you are getting a HTMLElement return type inference from document.createElement("svg") instead of SVGSVGElement.

like image 25
John Weisz Avatar answered Jan 03 '26 15:01

John Weisz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!