4

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.

2
  • @RobertLongson, I guess about this, but how we can set xmlns:xlink attribute? Commented May 12, 2016 at 8:17
  • @RobertLongson, wow, you right! Now all working and look fine. Can you format your previous comment as question for sharing you knowledge (it will be more noticeable)? Commented May 12, 2016 at 8:34

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Here we go:

// "circle" may be any tag name var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle"); // Set any attributes as desired shape.setAttribute("cx", 25); shape.setAttribute("cy", 25); shape.setAttribute("r", 20); shape.setAttribute("fill", "green"); // Add to a parent node; document.documentElement should be the root svg element. // Acquiring a parent element with document.getElementById() would be safest. document.documentElement.appendChild(shape); 

1 Comment

I need to do this without editing HTML. And creating circle I don't need too. Just use.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.