Skip to content

Commit

Permalink
Programmatically create SVG elements
Browse files Browse the repository at this point in the history
  • Loading branch information
jakelazaroff committed Dec 26, 2024
1 parent 7512e5f commit 8f75f95
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions javascript/programmatically-create-svg-elements.md
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);
```

0 comments on commit 8f75f95

Please sign in to comment.