Property 'width' Does Not Exist On Type 'HTMLElement'
Solution 1:
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 {}
Solution 2:
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
.
Solution 3:
In SVG width and height of elements are attributes and not CSS properties so you'd need to write
document.getElementById('cercle1').setAttribute("height", "10px");
similarly for the width.
Change height/width of object SVG javascript
In your case:
svg.setAttribute("width", "300px");
Solution 4:
Your question title is question "Property 'width' does not exist on type 'HTMLElement'"
HTMLElement
has no property width
it has property style
. and style
had width
let svg = document.createElement("svg");
svg.style.width = '30px';
In your case you need an SVGSVGElement
var svgEl = document.createElementNS("http://www.w3.org/2000/svg", "svg")
svgEl.width = 300
Post a Comment for "Property 'width' Does Not Exist On Type 'HTMLElement'"