SVG元素的outerHTML

ivk*_*mer 21 javascript svg dom outerhtml

为什么我们不能用element.outerHTML属性获取svg元素的outerHTML ?

这种方式是最好的http://jsfiddle.net/33g8g/获取svg源代码?

San*_*ahu 23

SVGElements没有outerHTML属性.

你可以在纯Javascript中定义这样的

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
});
Run Code Online (Sandbox Code Playgroud)

或者一行jQuery解决方案

$('<div>').append($(svgElement).clone()).html();
Run Code Online (Sandbox Code Playgroud)

参考:https: //gist.github.com/jarek-foksa/2648095

  • 我会在polyfill周围添加`if(!('outerHTML'在SVGElement.prototype中)){/***/}` (3认同)

Eri*_*röm 7

2013更新:根据DOM解析规范innerHTML,outerHTML也将支持svg元素.

此补丁已在Blink/Chrome中登陆,即将推出,请访问http://code.google.com/p/chromium/issues/detail?id=311080.

  • 我可以确认这在最新版本的Chrome,Safari和Firefox上都很完美.唉,它不适用于Internet Explorer 11. (3认同)

Tho*_*axl 7

这是一个更简单的解决方案,它在FF,Chrome,IE中非常有效。荣誉归Philipp Wrann所有

externalHtml在IE中不起作用

new XMLSerializer().serializeToString(document.querySelector('#b'))
Run Code Online (Sandbox Code Playgroud)


mjk*_*mjk 5

它不能通过outerHTML访问,因为SVG不是HTML - 它是一个单独的XML规范.

这就是为什么,例如,该示例中的svg节点有自己的命名空间(xmlns="http://www.w3.org/2000/svg).

您的示例可能是一次性查询最方便的,但实际上可以使用本机属性.它只需要更多的工作.

让我们使用链接的示例节点:

 <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <text x="0" y="15" fill="black">An SVG element.</text>
</svg> 
Run Code Online (Sandbox Code Playgroud)

如果要提取命名空间和版本,请使用该attributes属性.

var svgElement = $('svg')[0]; // using your example
console.log(svgElement.attributes.xmlns); // outputs "http://www.w3.org/2000/svg"
console.log(svgElement.attributes.version); // outputs "1.1"
Run Code Online (Sandbox Code Playgroud)

如果要提取实际内容,请迭代子项.与上面类似,非文本节点的attributes集合将包含x/y值(等).

不使用jQuery,再次使用您的示例:

for (var i = 0; i < svgElement.childNodes.length; i++) {
    var child = svgElement.childNodes[i];
    if (child.nodeType == 1) {
        console.log(child.attributes[0].name); // "x"
        console.log(child.attributes[0].value); // "0"
        console.log(child.attributes[1].name); // "y"
        console.log(child.attributes[1].value); // "15"
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个更新的小提琴,更优雅地展示了可能性:http: //jsfiddle.net/33g8g/8/