I am trying to draw an SVG rectangle using pure JavaScript. He does not appear.
But when I run document.getElementById('rect1')in 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 correctly. Therefore, it seems that the correct code is being added to the document, but the item is not displayed.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div>
<svg id="test" width="500" height="500">
</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();
source
share