denny
denny

Reputation: 197

change attribute of a svg in JavaScript

I have svg element loos like this where I took from google browser developer tool

took from google browser developer tool.

<svg>
  <g transform="translate(250,260) rotate(-90 0 0)">
    //......
  </g>
/svg>

SVG looks like this. I want to change the translate to (300,300)

I tried like this ,

svg.children[0].attributes("transform", "translate(" + 100 / 2 + "," + (100 / 2 + 10) + ") rotate(-90 0 0)");

but it gives attributes is not a function error. How may I do this.

Upvotes: 0

Views: 508

Answers (2)

guest271314
guest271314

Reputation: 1

.attributes does not accept parameters, but returns a NamedNodeMap which is a live collection of attribute nodes registered at the element. You can set the property directly following using document.querySelector(), Element.querySelector()

document.querySelector("svg")
.querySelector("g")
.transform = "translate(" 
             + 100 / 2 + "," 
             + (100 / 2 + 10) + ") rotate(-90 0 0)";
<svg>
  <g transform="translate(250,260) rotate(-90 0 0)">
  </g>
</svg>

Upvotes: 0

Steven10172
Steven10172

Reputation: 2013

Element.attributes is just a collection of all attributes registered to the element. To set an attribute use Element.setAttribute

https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes

https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute

Example: svg.children[0].setAttribute("transform", "translate(" + 100 / 2 + "," + (100 / 2 + 10) + ") rotate(-90 0 0)");

Upvotes: 1

Related Questions