Update: Yes, I know there are similar questions on SO, but the solutions don\'t work either.
I want to change SVG\'s color, I mean paths\'s color, n
The fill and/or stroke attribute on the path(s) do not override the CSS styling (here's why).
What you need to do is override the CSS styling itself, this can be done by setting the style property, e.g.
<path style="fill:green" ...>
Or in javascript
element.setAttribute('style', 'fill: green');
In your response to my comment you mentioned you'd address the 'single path' issue, in order to provide an example for that too here's why and how to fix it.
The querySelector method only provides the first element (if any) that matches, you want to use the querySelectorAll method, which will provide a NodeList containing all matching elements.
var paths = doc.querySelectorAll("path"),
i;
for (i = 0; i < paths.length: ++i) {
paths[i].setAttribute('style', 'fill:green');
}
As I mentioned in my comment, the getSVGDocument() method may not exist on all browsers you need to support (I know nothing about your requirements, this is just a heads up), you may be interested in the .contentDocument property as described here
What happens here is that the object is not a simple path, but actually the whole "stroke" has been transformed into a big object. This may happen when you export objects with fancy (or not so fancy) brush settings from various drawing applications. You can also get the same result with the Outline feature in Adobe Illustrator, IIRC.
To avoid this, edit the original object in its original illustration software and try the following:
Base on accepted answer, I created sample to click button and change color path.
Important thing:
I need host HTML file to webserver (IIS) to run it. If not it a.contentDocument always return null.
I share for whom concerned.
var svgDoc;
function changeColor() {
svgDoc = a.contentDocument;
// get the inner element by id
var paths = svgDoc.querySelectorAll("path");
// add behaviour
for (i = 0; i < paths.length; i++) {
paths[i].setAttribute('style', 'fill:pink');
}
}
var a = document.getElementById("alphasvg");
// It's important to add an load event listener to the object,
// as it will load the svg doc asynchronously
a.addEventListener("load", function () {
// get the inner DOM of alpha.svg
svgDoc = a.contentDocument;
// get the inner element by id
var paths = svgDoc.querySelectorAll("path");
// add behaviour
for (i = 0; i < paths.length; i++) {
paths[i].setAttribute('style', 'fill:green');
}
}, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<object data="test.svg" type="image/svg+xml" id="alphasvg"></object>
<button onclick="changeColor()">Change Color</button>
<script>
</script>
</body>
</html>