Basic SVG's with Javascript  

by ne on 2021-09-29 under Javascript

We all now are well aware of the extreme importance of a good client side portal for a website.
And how it's supremely powered by javascript and css.

But now a days a new concept is gaining strength. SVG.
Scalable Vector Graphics are fast, smooth and very attractive components that lure users to the webpage.

And they can be used wisely to create shapes, charts and much much more.

There are many libraries which will help you easily create and modify svg elements.

My personal favorite d3.js and snap.js.

Where d3 is much powerful, fully loaded javascript library capable of doing almost anything.

But if you wish to learn the basics, then here we go, with the main  motive of this blog post.

Creating SVG components with plain javascript.


var svg=document.createElementNS("", 'svg');
var circle=document.createElementNS("", 'circle');

The above code will make a circle with the attributes specified.

Now, when you will be using svg's on your page, then you will be needing a short hand function to do all the above.
Don't worry, I have provided a small-sized nice function for you:

function createShape(shape_,attributesJson) 
        var shape=document.createElementNS("", shape_);     
        var attr=JSON.parse(JSON.stringify(attributesJson)); 
        var keys=Object.keys(attr); 
        for(var i=0;i<keys.length;i++) { 
            var key=keys[i]; 
        return shape; 


So, Now with pure javascript, you can create SVG's. For example the above task of creating a cirlce and appending it to the svg can
now be done as




var svg=createShape('svg',{'height':h,'width':w});


More on svgs with javascript later.
Hope you enjoyed.. :)
And if you did, don't forget to upvote this post.