I am trying to modify the stroke and fill of an .svg image. I have been getting some information from Is it possible to manipulate an SVG document embedded in an HTML doc wi
I'm not sure if this has been resolved. I had experienced a similar scenario and the best way is to put the svg file in an <bject> tag and change the stroke property not fill property.
svgItem.style.stroke="lime";
Also you may refer to the section: Changing CSS Properties of SVG in this link
I had tested this and could change the stroke property. Please refer to this screnshot and below is the sample code which worked for me.
window.onload=function() {
// Get the Object by ID
var a = document.getElementById("svgObject");
// Get the SVG document inside the Object tag
var svgDoc = a.contentDocument;
// Get one of the SVG items by ID;
var svgItem = svgDoc.getElementById("pin1");
// Set the colour to something else
svgItem.style.stroke ="lime";
};
I've already answered something like this before, save this snippet as an html file.
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" style="width: 3.5in; height: 1in">
<circle id="circle1" r="30" cx="34" cy="34" style="fill: red; stroke: blue; stroke-width: 2"/>
</svg>
<button onclick=circle1.style.fill="yellow";>Click to change to yellow</button>
EDIT: To prove this function can be set in the head, here is a modified version:
<html>
<head>
<script>
function svgMod(){
var circle1 = document.getElementById("circle1");
circle1.style.fill="blue";
}
</script>
</head>
<body>
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" style="width: 3.5in; height: 1in">
<circle id="circle1" r="30" cx="34" cy="34" style="fill: red; stroke: blue; stroke-width: 2"/>
</svg>
<button onclick=circle1.style.fill="yellow";>Click to change to yellow</button>
<button onclick=jacascript:svgMod();>Click to change to blue</button>
</body>
</html>
If you use an img tag then for security reasons you will not be able to access the DOM of the image data. The image is effectively the same as an animated bitmap as far as the container is concerned.
Using an <iframe> or <object> tag will allow you to manipulate the embedded object's DOM.
Here is a simple example that demonstrates modifying an attribute of an SVG HTML object using javascript:
<html>
<body>
<svg>
<rect id="A1" x="10" y="10" width="25" height="25" fill="red" />
</svg>
</body>
<script>
alert("Acknowledge to modify object color.");
var object = document.getElementById("A1");
object.setAttribute("fill", "green");
</script>
</html>
I think you will need to modify the stroke of the individual element, not just the svg element itself. The svg will be composed of a tree of nodes, and it is these nodes which have the stroke attribute.