Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to change class name of SVG element

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.

like image 557
0aslam0 Avatar asked Jun 21 '16 11:06

0aslam0


3 Answers

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.

like image 64
Paul LeBeau Avatar answered Oct 23 '22 07:10

Paul LeBeau


The Version with setAttribute works for me. For className, you need baseVal in SVG:

document.getElementById("test").className.baseVal = "halffill";
like image 41
zayjuc Avatar answered Oct 23 '22 06:10

zayjuc


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.

like image 5
Pranoy Dey Avatar answered Oct 23 '22 07:10

Pranoy Dey