Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add SVG element to existing SVG using DOM

I have a HTML construction that resembles the following code:

<div id='intro'> <svg> //draw some svg elements <svg> </div> 

I want to be able to add some elements to the SVG defined above using javascript and DOM. How would I accomplish that? I was thinking of

var svg1=document.getElementById('intro').getElementsByTagName('svg'); svg1[0].appendChild(element);//element like <line>, <circle> 

I am not very familiar with using DOM, or how to create the element to be passed to appendChild so please help me out with this or perhaps show me what other alternatives I have to solve this issue. Thanks a lot.

like image 487
biggdman Avatar asked May 10 '13 18:05

biggdman


People also ask

Can you put an SVG inside an SVG?

The SVG format allows for the nesting of SVG graphics. It is possible for an “<svg>” elements, to be placed within another “<svg>” element. Though, within a nesting, the absolute placement is limited to the respective parent “<svg>” element.

How do I add elements to my DOM?

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

Is SVG a DOM element?

SVG documents in web browsers support the core DOM methods defined for all XML and HTML elements. For the most part, these core methods are the easiest and best-supported way to control the SVG DOM.

Does Z Index work with SVG?

The z-index only works on the complete content. This is because the HTML rendered controls the positioning before handing off to the SVG rendered to place the internal SVG contents. So, basically there is no z-index for SVG, it uses the painters model.


1 Answers

If you want to create an HTML element, use document.createElement function. SVG uses namespace, that's why you have to use document.createElementNS function.

var svg = document.getElementsByTagName('svg')[0]; //Get svg element var newElement = document.createElementNS("http://www.w3.org/2000/svg", 'path'); //Create a path in SVG's namespace newElement.setAttribute("d","M 0 0 L 10 10"); //Set path's data newElement.style.stroke = "#000"; //Set stroke colour newElement.style.strokeWidth = "5px"; //Set stroke width svg.appendChild(newElement); 

This code will produce something like this:

<svg>  <path d="M 0 0 L 10 10" style="stroke: #000; stroke-width: 5px;" /> </svg> 



createElement: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

createElementNS: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS

like image 115
m93a Avatar answered Oct 18 '22 17:10

m93a