Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create SVG element via javascript

I need to create this structure using only javascript:

<svg>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#circle"></use>
</svg>

But I have trouble with creating xmlns:xlink attribute. Here is my js code:

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
// throws error here
use.setAttributeNS('http://www.w3.org/2000/xmlns', 'xmlns:xlink', 'http://www.w3.org/1999/xlink');
use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#circle');
svg.appendChild(use);

If I comment string with settings xmlns:xlink all working good and makes svg same as above, but without xmlns:xlink.

I seen a lot of question similar to mine, but they didn't solve my problem.

like image 647
cassln Avatar asked Apr 27 '26 11:04

cassln


1 Answers

Regarding

use.setAttributeNS('http://www.w3.org/2000/xmlns', 'xmlns:xlink', 'http://www.w3.org/1999/xlink');

You don't need that line and actually it's not valid.

The xmlns:xlink attribute set automatically when you create an element with createElementNS or an attribute with setAttributeNS if you're creating an element/attribute in an XML document and it's not required if you're creating an element in a html document.

like image 158
Robert Longson Avatar answered Apr 29 '26 00:04

Robert Longson



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!