3

I have the JavaScript file. I have the SVG file. Also I have HTML file.

<head>
...
<link rel="stylesheet" href="style.css" type="text/css" charset="utf-8">
...
</head>
<body>
...
<img src='svgfile.svg' type='image/svg+xml' />
...
</body>

Anyone knows how I can call the element of SVG in JavaScript? (circle for example)

  • 1
    Maybe you can use this answer: http://stackoverflow.com/questions/2753732/how-to-access-svg-elements-with-javascript – Stephan Feb 16 '14 at 18:20
  • Note that you can't access the contents of an `` element, you'd need to use an `` or ` – Robert Longson Feb 16 '14 at 20:16

1 Answers1

2

If you want to dynamically interact, using Javascript, with the svg file which is loaded into your HTML5 page, you must load the svg as inline. If you load as an <object> you cannot program it using your javascript. However you can load the svg file as xml via XMLHttpRequest and fill a DIV's innerHTML with the response. This inline SVG then can be dynamically changed via your Javascript. This works across all browsers. Try the files below.

Assume you have an SVG file(my.svg)

<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400">
<circle id="myCircle" cx="200" cy="200" fill="blue" r="150" />
</svg>

and your HTML5 file is as below:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<center>
<div id="svgInlineDiv" style='background-color:lightgreen;width:400px;height:400px;'></div>
<button onClick=changeInlineCircleColor()>Change Circle Color</button>
<div id="svgObjectDiv" style='background-color:lightblue;width:400px;height:400px;'>
<object data="my.svg" type="image/svg+xml" id="objsvg" width="100%" height="100%"></object>
</div>
</center>
<script id=myScript>
function changeInlineCircleColor()
{
    myCircle.setAttribute("fill","red")
}
</script>
<script>
document.addEventListener("onload",inlineSVG(),false)
function inlineSVG()
{
    var SVGFile="my.svg"
    var loadXML = new XMLHttpRequest;
    function handler(){
    if(loadXML.readyState == 4 && loadXML.status == 200)
        svgInlineDiv.innerHTML=loadXML.responseText
    }
    if (loadXML != null){
        loadXML.open("GET", SVGFile, true);
        loadXML.onreadystatechange = handler;
        loadXML.send();
    }
}
</script>
</body>
</html>
Francis Hemsher
  • 3,478
  • 2
  • 13
  • 15