views:

175

answers:

3

I'm trying to append a string of svg elements to the dom. This is my setup.

var oFragment = '';
for (var i = 0; i < 10; i++) {
oFragment += '<g><path id="note-'+i+'" d="M 6,3 84,6  c 0,0 -6,76 14,91  L 58,97 19,89  c 0,0 -24,-5 -13,-86 z" style="fill:#ffc835;" /></g> ';
}

Here is what i tried. It gives the following error: "parseXML is not defined"

var oSVG = document.getElementById("svg-wall").getSVGDocument();
var oNotes = oSVG.getElementById('notes');
oNotes.appendChild(parseXML(oFragment, document));

So my question is: what am i doing wrong and is this even the best way to append a svg string to the dom?

A: 

Well, at least you are generating 10 elements with the same id.

Vasily Korolev
hahaha oops fixed that :P
Wieringen
A: 

I don't think there's a free function called parseXML (are you missing some functions?).

And since you're dealing with DOM anyway, just not directly insert the elements with DOM?

for (var i = 0; i < 10; ++ i) {
   var path = document.createElement("path");
   path.setAttribute("id", "note-" + i);
   ...
   var g = document.createElement("g");
   g.appendChild(path);
   oNotes.appendChild(g);
}
KennyTM
thx! ok i will do it that way. i was hoping for a quicker shorter solution like innerHTML or html() in jquery. There is a root element im inserting it in a <g>.
Wieringen
@Wieringen: No you're creating 10 `<g>`'s.
KennyTM
i know but oNotes is a g with the id notes
Wieringen
@Wieringen: Ah so it's `<g><g><path.../></g><g>...</g></g>`? I think that's fine then.
KennyTM
Yep :) it works!!! only i needed to replace createElement() with createElementNS('http://www.w3.org/2000/svg', 'g');
Wieringen
+1  A: 

parseXML is part of SVG Tiny 1.2, but the SVGGlobal interface methods are not supported in any web browsers at the moment AFAIK. It's entirely possible to implement it using other technologies however. If you look at the bottom of this blogpost of mine, SVG at the movies take 2, you'll find a simple wrapper script that implements parseXML (should work fine in opera, firefox and webkit). For examples of this script being used have a look at the source of the demos in that blogpost.

Erik Dahlström