-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Programmatically create SVG elements
- Loading branch information
1 parent
7512e5f
commit 8f75f95
Showing
1 changed file
with
24 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
# Programmatically create SVG elements | ||
|
||
This is simple, but it tripped me up for a bit. TL;DR you can't do this: | ||
|
||
```js | ||
const svg = document.createElement("svg"); | ||
const line = document.createElement("line"); | ||
svg.append(line); | ||
``` | ||
|
||
I mean, you can, but it won't work. These will both throw exceptions: | ||
|
||
```js | ||
console.assert(svg instanceof SVGSVGElement, "%o is an SVG element", svg); | ||
console.assert(line instanceof SVGLineElement, "%o is an SVG element", svg); | ||
``` | ||
|
||
What you need instead is [`document.createElementNS`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS): | ||
|
||
```js | ||
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); | ||
const line = document.createElementNS("http://www.w3.org/2000/svg", "line"); | ||
svg.append(line); | ||
``` |