I want to change the class applied on an SVG with the click of a button. The code is here .
My SVG looks like:
<svg id="test" class="fill" xmlns="http://www.w3.org/2000/svg" width="100%" height="200px" >
<path id="path22276" d="m500 81c-41-6-110-35-110-46 0-6 32 6 48 19 8 5 53 12 101 14 78 4 93 1 144-22 32-14 60-26 64-26 8 0-37 34-62 47-28 15-131 22-185 14z"/>
</svg>
I tried both the below code :
document.getElementById("test").className = "halffill";
document.querySelector("svg.fill").setAttribute("class","halffill");
I tested the same javascript code against a normal div tag. It worked fine. Is there some restriction on SVG? Please help me figure this out.
The className
property on an SVG element has a different definition from the className
property of an HTML element.
In HTML, className
is a string. In SVG it is an SVGAnimatedString
object. That's why you can't just do svgElement.className = "halffill"
.
However, the second line (using setAttribute()
) should work.
The Version with setAttribute
works for me. For className
, you need baseVal
in SVG:
document.getElementById("test").className.baseVal = "halffill";
The thing is that javascript doesn't update in source code. You need to check the change in the inspect mode. First one didn't work for me either but the second one works.
document.querySelector("svg.fill").setAttribute("class","halffill");
Click on the button that is intended to change the name of the class and then go to inspect mode and check the class name of svg tag
Note : To go to inspect mode right click anywhere on the screen and click on Inspect or use ctrl + shift + I in google chrome in windows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With