0

Im trying to display the attribute value of circle but its not working.

My Script

var x = document.getElementById("circle").getAttribute("cx");
document.write(x);

My HTML

<svg width="1000" height="500">
    <circle id="circle" cx="50" cy="50" r="50">
</svg>
Mark Baijens
  • 13,028
  • 11
  • 47
  • 73

3 Answers3

1

The circle element should be self closing.

var x = document.getElementById("circle").getAttribute("cx");
document.write(x);
<svg width="1000" height="500">
  <circle id="circle" cx="50" cy="50" r="50" />
</svg>

You need to scroll down in the snippet window above due to your SVG width and height.

Ash
  • 11,292
  • 4
  • 27
  • 34
0

Your code is working as intended in my snippet. Something else is causing your problem.

Note that the value 50 is pretty far below to circle so you have to scroll a bit.

What could be the case is that your javascript runs before the dom is fully loaded. Add your code to the body onload event handler.

var x = document.getElementById("circle").getAttribute("cx");
document.write(x);
<svg width="1000" height="500">
    <circle id="circle" cx="50" cy="50" r="50">
</svg>
Mark Baijens
  • 13,028
  • 11
  • 47
  • 73
  • @zer00ne That's not the problem. It work's fine with the big svg as you can see in my snippet. It just places the value on the bottom of the document. If you change the `position` with css to absolute/relative/etc it could be placed over it. But it's not that case here. – Mark Baijens Jul 10 '18 at 08:34
  • 1
    @zer00ne Yeah i know what you mean. It does exactly the same as OP's code accept it shows a smaller svg. It's adds absolutely nothing to the problem. If the OP wants a big svg for whatever reason it's perfectly valid and works fine. – Mark Baijens Jul 10 '18 at 08:42
  • @zer00ne Well most answers in here say he needs to scroll down. I Don't see the added value of your answer. I think it's even worse then most answers here since it suggest that the problem is the size of the svg. Which it is not. – Mark Baijens Jul 10 '18 at 08:47
0

If i understand your problem correctly, you try to access a svg element from your html Javascript. If your problem is this one see the answer below :

How to access SVG elements with Javascript