Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SVGElement.prototype.innerHTML shim
// Important: You must serve your pages as XHTML for this shim to work,
// otherwise namespaced attributes and elements will get messed up.
Object.defineProperty(SVGElement.prototype, 'innerHTML', {
get: function() {
var $child, $node, $temp, _i, _len, _ref;
$temp = document.createElement('div');
$node = this.cloneNode(true);
_ref = $node.children;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
$child = _ref[_i];
$temp.appendChild($child);
}
return $temp.innerHTML;
},
set: function(markup) {
var $div, $element, $svg, _i, _len, _ref, _results;
while (this.firstChild) {
this.firstChild.parentNode.removeChild(this.firstChild);
}
markup = "<svg id='wrapper' xmlns='http://www.w3.org/2000/svg'>" + markup + "</svg>";
$div = document.createElement('div');
$div.innerHTML = markup;
$svg = $div.querySelector('svg#wrapper');
_ref = $svg.children;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
$element = _ref[_i];
_results.push(this.appendChild($element));
}
return _results;
},
enumerable: false,
configurable: true
});
@Nippey

This comment has been minimized.

Copy link

Nippey commented Dec 12, 2012

At line 14, do you mean the following?

this.firstChild.parentNode.removeChild(this.firstChild);
@jarek-foksa

This comment has been minimized.

Copy link
Owner Author

jarek-foksa commented Jan 23, 2013

Yeah, I have updated the code. There was also another bug that caused the shim to behave like outerHTML.

@sbrown345

This comment has been minimized.

Copy link

sbrown345 commented Feb 21, 2013

Modified for outerHTML:

Object.defineProperty(SVGElement.prototype, 'outerHTML', {
    get: function () {
        var $node, $temp;
        $temp = document.createElement('div');
        $node = this.cloneNode(true);
        $temp.appendChild($node);
        return $temp.innerHTML;
    },
    enumerable: false,
    configurable: true
});
@nuxodin

This comment has been minimized.

Copy link

nuxodin commented Apr 9, 2015

In Safari, svg elements have no "children" attribute, i use "childNodes" instead

@munir131

This comment has been minimized.

Copy link

munir131 commented Jun 23, 2015

In get function _ref.length is decrease after every iteration of for loop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.