Reputation: 123
I am trying to write a script that will dynamically create an SVG element and display it. However, when I set the ID of the SVG element and then try to access it with Document.getElementById(), it returns null. I am using window.onload to make sure that the document will have loaded before calling the script.
<body>
<script>
function buildSVG(color) {
const shape = `<rect x="0" y="0" width="90" height="90" stroke="black" fill="${color}"/>`;
return shape;
}
function addSVG(color) {
let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.id = "svgID";
let elem = document.getElementById("svgID");
elem.setAttribute('width', '600');
svg.setAttribute('height', '250');
svg.innerHTML = buildSVG(color);
svg.setAttribute('style', 'border: 1px solid black');
document.body.appendChild(svg);
}
window.onload = addSVG("cyan");
</script>
</body>
I would expect a cyan square to be displayed. However, I get the error "cannot read property setAttribute of null".
What can I do to fix this?
Upvotes: 0
Views: 996
Reputation: 2853
When you create your svg-element you already have a reference to it in the variable you assigned. No need to get it again from the document. That would even not be possible, since it is not yet added to the document. Here is the corrected code:
function buildSVG(color) {
const shape = `<rect x="0" y="0" width="90" height="90" stroke="black" fill="${color}"/>`;
return shape;
}
function addSVG(color) {
let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.id = "svgID";
svg.setAttribute('width', '600');
svg.setAttribute('height', '250');
svg.innerHTML = buildSVG(color);
svg.setAttribute('style', 'border: 1px solid black');
document.body.appendChild(svg);
}
window.onload = addSVG("cyan");
// after 1 second: get the svgID-element and change the border.
setTimeout(function(){
document.getElementById('svgID').setAttribute('style', 'border: 1px dashed red');
}, 1000);
Upvotes: 2