为什么不能获取带有element.outerHTML
属性的svg元素的outerHTML?
这种方式是获取svg源代码的最佳http://jsfiddle.net/33g8g/吗?
发布于 2013-09-17 00:02:37
不能通过outerHTML访问它,因为SVG不是HTML语言--它是一个单独的XML specification。
例如,这就是为什么示例中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>
如果要提取命名空间和版本,请使用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"
如果您想提取实际内容,请遍历子对象。与上面类似,非文本节点的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"
}
}
这是一个更新的提琴,更优雅地展示了各种可能性:http://jsfiddle.net/33g8g/8/
发布于 2013-12-13 13:39:50
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
});
或者一行jQuery解决方案将是
$('<div>').append($(svgElement).clone()).html();
发布于 2017-07-15 23:54:00
这是一个更简单的解决方案,它在FF,Chrome,IE中工作得很好。荣誉属于Philipp Wrann。
outerHtml is not working in IE
new XMLSerializer().serializeToString(document.querySelector('#b'))
https://stackoverflow.com/questions/12592417
复制相似问题