svgでつまらないことに躓いたこと
svgに動的に生成したelementを追加しようとしてなんかつまらないことで躓いたのでメモしておきます。
つまらなすぎて辛かったので勢いで書いた記事です。
- index.svg
<?xml version="1.0" encoding="utf-8"?> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" onload="main()" id="svg" > <script xlink:href="main.js"/> </svg>
- main.js
svg = document.getElementById('svg'); var xmlns = "http://www.w3m.org/2000/svg"; SVGObj = function(elem){ this.elem = elem; this.setAttribute = function(key, value){return this.elem.setAttributeNS(null, key, value)}; }; utils = {}; utils.createElement = function(tagname){ var elem= document.createElementNS(xmlns,tagname); var obj = new SVGObj(elem); var res = function(){return obj.elem}; res.__proto__ = obj; return res; }; test1 = function(){ var r = document.createElementNS(xmlns,'rect'); r.id = 'testchan' r.setAttributeNS(null,'width',100); r.setAttributeNS(null,'height',100); document.documentElement.appendChild(r) } test2 = function(){ var rect = utils.createElement('rect'); rect.elem.id = 'rect'; rect.setAttribute('x',100); rect.setAttribute('y',100); rect.setAttribute('width',100); rect.setAttribute('height',100); rect.setAttribute('fill','red'); document.documentElement.appendChild(rect()); }; main = function(){ test1() test2() };
これを実行しても何も表示されません。
でも、developper toolsにはdomは生成されているのは確認できて、document.getElementById('rect')をしたら取得できます。
答えはcreateElementした時の名前空間。
var xmlns = "http://www.w3m.org/2000/svg";
w3m.orgってなんじゃああああああブラウザじゃないんだよおおおおお
そんな感じで1時間潰したわけでした。ちゃんちゃん。