I’m having some trouble with manipulating SVGs through javascript. I’d like to increase the length of a line through clicking a button. I’ve included this code in the head tag:
<script type="text/javascript">
x=135;
y=135;
var container = document.getElementById("svgbox");
var mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
function svg() {
mySvg.setAttribute("version", "1.2");
mySvg.setAttribute("baseProfile", "tiny");
mySvg.setAttribute("height","300px");
mySvg.setAttribute("width","300px");
container.appendChild(mySvg);
}
function line() {
x=x-10;
y=y-10;
var L1 = document.createElementNS("http://www.w3.org/2000/svg", "line");
L1.setAttribute("x1", "100"); L1.setAttribute("y1", "100");
L1.setAttribute("x2", x); L1.setAttribute("y2", y);
L1.setAttribute("stroke", "#05adc7");
L1.setAttribute("stroke-width", "2px");
mySvg.appendChild(L1);
}
</script>
This is the body text:
<body onload="svg()">
<form>
<input type="button" onClick="line()" />
</form>
<div id="svgbox">
</div>
</body>
But when I click on the button, I get an error telling me that the variable “container” is null. Does anyone know what the problem is?
It works if you put the line
var container = document.getElementById("svgbox");in the svg function.The reason container is
nullin your code is because the DOM has not loaded yet when the linevar container = document.getElementById("svgbox");gets executed.You need to declare container after either the
DOMContentLoadedevent orwindow.onloadevent is fired.