akm
akm

Reputation: 465

Get width or height svg rectangle javascript

I can get the width of my object svg in javascript and save the value in a variable. this is my object

    <rect id="cercle1" x="5" y="25" width="50" height="50"  stroke-width="1" stroke="#0E0E0E" style="fill:red; stroke:black; stroke-width:2"; />

I try this:

document.getElementById('cercle1').width.value;

thanks for help

Upvotes: 4

Views: 14765

Answers (4)

0xFK
0xFK

Reputation: 2718

Just in case you had created your rect dynamically, then the below solution is valid

var rect = document.createElementNS(svgns, "rect");
rect.setAttribute('width', '200px');
rect.setAttribute('height', '200px');
var width= rect.width.baseVal.value;
var height= rect.width.baseVal.value;

Upvotes: 1

blex
blex

Reputation: 25634

You can use the getAttribute function:

document.getElementById('cercle1').getAttribute("width");

That will get you the String from the HTML code. As Phrogz mentioned it, you might want a number instead, or the actual value (that might be different). If so, refer to his answer.

Upvotes: 8

Bura Chuhadar
Bura Chuhadar

Reputation: 3751

You can try this:

var obj = document.getElementById("cercle1"); // reference to the object tag
var rect = obj.getBoundingClientRect(); // get the bounding rectangle
alert(rect.width);
alert(rect.height);

Or this:

var obj = document.getElementById("cercle1"); // reference to the object tag
var svgdoc = obj.contentDocument; // reference to the SVG document
var svgelem = svgdoc.documentElement; // reference to the SVG element
alert(svgelem.getAttribute("width"));

Here is a working JSFiddle example.

From the comments from Phrongz: Note that the bounding rect will account for transforms, which may or may not be desired.

Upvotes: 4

Phrogz
Phrogz

Reputation: 303168

The width attribute is an SVGAnimatedLength property. As such, you need to:

// If you want the original value
var w = document.getElementById('cercle1').width.baseVal.value;

// If it is animated and you want the current animated value
var w = document.getElementById('cercle1').width.animVal.value;

Or, if just want what's in the source code:

var w = document.getElementById('cercle1').getAttribute('width')*1; // convert to num

Upvotes: 6

Related Questions