Create SVG with JavaScript

In this example, an SVG <text> element is generated using JavaScript

SVG Rendered:

SVG Generated:

<svg width="100%" height="120" id="svgDoc"><text y="40" x="20">Hello World! This is SVG text created with JavaScript.</text></svg>

JavaScript Source:

<script>
	var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
	svg.setAttributeNS(null,"id","svgDoc");
	svg.setAttributeNS(null,"height","120");
	svg.setAttributeNS(null,"width","100%");
	
	document.getElementsByTagName('body')[0].appendChild(svg);
	var svgDoc = document.getElementById('svgDoc');
	
	var txtElem = document.createElementNS("http://www.w3.org/2000/svg", "text");
	txtElem.setAttributeNS(null,"x",20);
	txtElem.setAttributeNS(null,"y",40);
	
	var theText = "Hello World! This is SVG Text created with JavaScript.";
	var theMSG = document.createTextNode(theText);
	txtElem.appendChild(theMSG);
	 
	svgDoc.appendChild(txtElem);
</script>

Obviously, it would be easier to simply write this in XML. However, the purpose of this was to examine how JavaScript could be used to generate SVG on the fly.