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.
If you want to create an HTML element, use
document.createElement
function. SVG uses namespace, that's why you have to usedocument.createElementNS
function.This code will produce something like this:
createElement
: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementcreateElementNS
: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNSIf you're dealing with svg's a lot using JS, I recommend using d3.js. Include it on your page, and do something like this: