user4075830
user4075830

Reputation: 87

Reference SVG file to SVG object in JavaScript

My question is how can I refer to a SVG file with a SVG object created with javascript ? What I'm trying to do so far does not seem to work

  var svg = document.getElementById("svg");
	  svg.setAttribute('width', '2048');
	  svg.setAttribute('height', '784'); 

  var background = document.createElementNS("http://www.w3.org/2000/svg", "svg");
	  background.setAttribute('width', '2048');
	  background.setAttribute('height', '784');
	  background.setAttributeNS('http://www.w3.org/1999/xlink', 'href', 'myimg.svg');
	  background.setAttribute('x', '0');
	  background.setAttribute('y', '0');	

svg.appendChild(background);	
svg
{
	border-style: solid;
    border-width: 5px;
}
<body>
	<svg id="svg"></svg>		
</body>

Upvotes: 0

Views: 821

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

Have a look at this code

var svgDocument, svg;
var obj=document.createElement('object');
obj.addEventListener('load', function(e) {
    svgDocument = this.contentDocument;
    svg = svgDocument.querySelector('svg');
});
obj.data = 'myimg.svg';
document.body.appendChild(obj);

You create an object with data set to your svg file. onload, the "root" element (the svg element) can be obtained as shown

Note: you can't access contentDocument until the svg has loaded.

Upvotes: 3

Related Questions