views:

39

answers:

1

I need to insert a DOM which is a complete SVG document into an <object> element. SO here's my code:

var svgDom   = (new DOMParser()).parseFromString(streamedFile,'image/svg+xml');
var pagePics = document.querySelectorAll('#currentFiles figure object');

for (var i=0; i<pagePics.length; i++){
    pagePics[i].contentDocument = svgDom.document;
}

But this doesn't work. DOM inspector doesn't show <object>'s contentDocument property after this code has run.

It's possible to use jQuery if this makes things easier. What am i doing wrong?

+1  A: 

contentDocument is a read-only attribute. You can't move Document​s from one context to another.

Usually you'd have to importNode content from one document into another. However that's of little use if you've got different document types like SVG and HTML.

For loading SVG from a string string into an iframe or object, I'd think you'd have no choice but to create the element with a data: URL, eg. <object data="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E...">.

bobince
Thanks! And is it possible to create a new `object` element with the DOM i have and replace the old one? And if it's impossible, won't it be too much load to serialize DOM, url_escape it and then unescape the escaped string?
Spadar Shut
Yes, it should be possible to create an `object` dynamically. Of course neither `data:` URLs nor `querySelectorAll` will work on IE6-7, but then if we're talking SVG I guess we're not talking about IE...
bobince
But can we assign the DOM to a dynamically created `object`? I guess no, for if it's read-only attribute it should not matter if the object in the DOM already or not.But what about the performace? Or since i have no options need not bother about it?I'm making an Opera svg viewer widget, so IE is not a question. It's like coding paradise I should say :)!
Spadar Shut
No, you'd assign the `encodeURIComponent`-ed string in a `data:` URL to the `data` property of the new or existing `object`.
bobince
How would you style or get elements by IDs in the SVG then? data: URIs can't use IDs.
Eli Grey
@Elijah: I'm not sure I see the problem you're referring to. You can certainly call `object.contentDocument.getElementById()` et al to interact with an SVG DOM inside an `<object>` element loaded from a `data:` URL.
bobince
I've found that data URI method is extremely resource-expensive, especially when a lot of objects need to be processed this way.
Spadar Shut
Will importNode work in an xhtml documet with svg and xhtml namespaces?
Spadar Shut