1

So, I have this svg.

<svg width="0" height="0"><clippath id="4vIt5" clippathunits="objectBoundingBox"><path d="
        M 0.15, 0.15
        L 0.35,0.15
        C 0.35 0.15 0.65 0.15 0.65 0.15 
        L .85,0.15
        L 0.85,0.35
        C 0.7 0.35 0.7 0.65 0.85 0.65
        L 0.85, 0.85
        L 0.65, 0.85
        C 0.65 1 0.35 1 0.35 0.85 
        L 0.15, 0.85
        L 0.15, 0.65
        C 0.15 0.65 0.15 0.35 0.15 0.35 
        L 0.15, 0.15
        "></path></clippath></svg>

When I put this in html (exact same) and when I link the div to this clip path like

clip-path: url(#4vIt5)

It is worrking fine

But when I dynamically create this svg using JS like

let svg = document.createElement('svg')
let clipPath = document.createElement ('clipPath')
let path = document.createElement('path')
path.setAttribute('d' `.....`)

append it the svg is clearly working and coming in the html document. I can see it from inspect element. The svg is appearing correctly, But the link is not working i.e. when I try to link the svg id to div

clip-path: url('#id')

Now it is not working. How is this possible?

I have tested it like following.

  1. I copied exact same svg from dynamically created svg using inspect window and pasted to the html document
  2. It is working absolutely fine

the problem is while doing the same thing dynamically

1 Answers1

1

You need to use createElementNS() so that the SVG elements are created in the SVG namespace. Otherwise they'll be created in the default HTML namespace.

let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
let clipPath = document.createElementNS('http://www.w3.org/2000/svg', 'clipPath')
let path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
path.setAttribute('d' `.....`)
Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181