These are a couple of tests on SVG and DOM that I've made a long time ago. In the first test, I'm simply checking whether it's possible or not to create a svg
element with attributes and styles. The attached styles are:
div[id="test"] { width: 200px; height: 200px; background-color: red; } svg, rect { display: block; } rect { width: 200px; height: 200px; background-color: green; }
and the JavaScript code is:
window.onload = function () { var test = document.getElementById("test"); var svg = document.createElement("svg"); svg.setAttribute("width", "200"); svg.setAttribute("height", "200"); svg.setAttribute("version", "1.1"); svg.setAttribute("xmlns", "http://www.w3.org/2000/svg"); test.appendChild(svg); var rect = document.createElement("rect"); rect.setAttribute("x", "0"); rect.setAttribute("y", "0"); rect.setAttribute("width", "200"); rect.setAttribute("height", "200"); rect.setAttribute("fill", "green"); svg.appendChild(rect); };
You can see this test here. It works fine in all supporting browsers. In the second test, instead, I have the following markup:
<div id="test"> <svg width="200" height="200" version="1.1" xmlns="http://www.w3.org/2000/svg"> <rect x="0" y="0" width="200" height="200" /> </svg> </div>
with the following styles:
div[id="test"] { width: 200px; height: 200px; background-color: red; }
I want to test whether it's possible to set a SVG style attribute via the DOM. The JavaScript code is as follows:
window.onload = function () { var rect = document.getElementsByTagName("rect")[0]; rect.setAttribute("fill", "green"); };
You can see this test here. It works fine in all supporting browsers. In the third and last test I have the same markup showed above. What I want to demonstrate is simple: setting a CSS rule via the DOM by using a SVG style property. Here's the JavaScript code:
window.onload = function () { return document.styleSheets[0].insertRule("rect {fill: green}", document.styleSheets[0].cssRules.length); };
You can see this test here. It works fine in all supporting browsers.