10

I'm trying to draw an SVG rectangle with pure JavaScript. It's not showing up.

But when I run document.getElementById('rect1') in the the browser console, the rectangle element exists. And when I copy and paste the HTML from the console into the HTML file, the rectangle displays properly. So it seems as though the correct code is being added to the document, but the element isn't being displayed.

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <div>
      <svg id="test" width="500" height="500">
          <!-- code copied from browser console works 
          <rect x="30" y="60" width="50" height="80" style="stroke:#000000; fill:none;" id="rect1">
         </rect> -->
     </svg>

      <svg id="main" width="500" height="500"></svg>
    </div>
    <script src="./src/shapes.js"></script>
  </body>
</html>

JavaScript:

function addSvgElement() {
    var rect = document.createElement("rect");
    rect.setAttribute('x', 30);
    rect.setAttribute('y', 60);
    rect.setAttribute('width', 50);
    rect.setAttribute('height', 80);
    rect.setAttribute('style', "stroke:#000000; fill:none;");
    rect.id = "rect1";
    var svg = document.getElementById('main');
    svg.appendChild(rect);
}

addSvgElement(); // adds correct code, but element doesn't show up
Patrick Brinich-Langlois
  • 1,381
  • 1
  • 15
  • 29
  • 1
    looks like it works...http://jsfiddle.net/fpG4Z/ – sfletche May 11 '14 at 02:43
  • possible duplicate of [Creating SVG graphics using javascript?](http://stackoverflow.com/questions/1034712/creating-svg-graphics-using-javascript) – Felix Kling May 11 '14 at 02:46
  • @sfletche Sorry, I didn't make it clear that the code in the HTML file that was generating the rectangle was copied from the browser console and pasted into the document for debugging. I wanted to generate the rectangle dynamically, though. – Patrick Brinich-Langlois May 11 '14 at 02:51

1 Answers1

28

document.createElement("rect"); will create an unknown HTML DOM element. You have to use the correct namespace to create an SVG DOM element.

var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143