2012-09-25 150 views

回答

4

它不能通过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/

19

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(); 

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

+0

感谢分享这 - 是具有一个时间赫克得到outerHTML在Safari中工作! – aendrew

+0

我会在polyfill –

6

2013更新:innerHTMLouterHTML将被svg eleme支持nts也是,每DOM Parsing specification

此修补程序已在Blink/Chrome中着陆,很快就会发布,请参阅http://code.google.com/p/chromium/issues/detail?id=311080

+0

的周围添加if(!('SVGlement.prototype的outerHTML')){/ ** * /}哇,这很好。 – ivkremer

+3

我可以确认这适用于最新版本的Chrome,Safari和Firefox。唉,它不适用于Internet Explorer 11。 – Husky

1

使用jQuery,您可以轻松地创建周围的任何元素的临时HTML包装,不支持outerHTML:

function wrappedHtml(elt){ 
    var wrapped = elt.wrap("<wrap></wrap>").parent().html(); 
    elt.unwrap(); 
    return wrapped; 
} 
1

这是一个简单的解决方案,它在FF,Chrome浏览器,IE浏览器的伟大工程。荣誉去Philipp Wrann

outerHtml is not working in IE

new XMLSerializer().serializeToString(document.querySelector('#b'))